es6.js 4.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104
  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. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7445. if (mimeType === void 0) { mimeType = "image/png"; }
  7446. if (samples === void 0) { samples = 1; }
  7447. if (antialiasing === void 0) { antialiasing = false; }
  7448. var width;
  7449. var height;
  7450. //If a precision value is specified
  7451. if (size.precision) {
  7452. width = Math.round(engine.getRenderWidth() * size.precision);
  7453. height = Math.round(width / engine.getAspectRatio(camera));
  7454. size = { width: width, height: height };
  7455. }
  7456. else if (size.width && size.height) {
  7457. width = size.width;
  7458. height = size.height;
  7459. }
  7460. else if (size.width && !size.height) {
  7461. width = size.width;
  7462. height = Math.round(width / engine.getAspectRatio(camera));
  7463. size = { width: width, height: height };
  7464. }
  7465. else if (size.height && !size.width) {
  7466. height = size.height;
  7467. width = Math.round(height * engine.getAspectRatio(camera));
  7468. size = { width: width, height: height };
  7469. }
  7470. else if (!isNaN(size)) {
  7471. height = size;
  7472. width = size;
  7473. }
  7474. else {
  7475. Tools.Error("Invalid 'size' parameter !");
  7476. return;
  7477. }
  7478. var scene = camera.getScene();
  7479. var previousCamera = null;
  7480. if (scene.activeCamera !== camera) {
  7481. previousCamera = scene.activeCamera;
  7482. scene.activeCamera = camera;
  7483. }
  7484. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7485. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7486. texture.renderList = null;
  7487. texture.samples = samples;
  7488. if (antialiasing) {
  7489. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7490. }
  7491. texture.onAfterRenderObservable.add(function () {
  7492. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7493. });
  7494. scene.incrementRenderId();
  7495. scene.resetCachedMaterial();
  7496. texture.render(true);
  7497. texture.dispose();
  7498. if (previousCamera) {
  7499. scene.activeCamera = previousCamera;
  7500. }
  7501. camera.getProjectionMatrix(true); // Force cache refresh;
  7502. };
  7503. // XHR response validator for local file scenario
  7504. Tools.ValidateXHRData = function (xhr, dataType) {
  7505. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7506. if (dataType === void 0) { dataType = 7; }
  7507. try {
  7508. if (dataType & 1) {
  7509. if (xhr.responseText && xhr.responseText.length > 0) {
  7510. return true;
  7511. }
  7512. else if (dataType === 1) {
  7513. return false;
  7514. }
  7515. }
  7516. if (dataType & 2) {
  7517. // Check header width and height since there is no "TGA" magic number
  7518. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7519. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7520. return true;
  7521. }
  7522. else if (dataType === 2) {
  7523. return false;
  7524. }
  7525. }
  7526. if (dataType & 4) {
  7527. // Check for the "DDS" magic number
  7528. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7529. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7530. return true;
  7531. }
  7532. else {
  7533. return false;
  7534. }
  7535. }
  7536. }
  7537. catch (e) {
  7538. // Global protection
  7539. }
  7540. return false;
  7541. };
  7542. /**
  7543. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7544. * Be aware Math.random() could cause collisions, but:
  7545. * "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"
  7546. */
  7547. Tools.RandomId = function () {
  7548. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7549. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7550. return v.toString(16);
  7551. });
  7552. };
  7553. Object.defineProperty(Tools, "NoneLogLevel", {
  7554. get: function () {
  7555. return Tools._NoneLogLevel;
  7556. },
  7557. enumerable: true,
  7558. configurable: true
  7559. });
  7560. Object.defineProperty(Tools, "MessageLogLevel", {
  7561. get: function () {
  7562. return Tools._MessageLogLevel;
  7563. },
  7564. enumerable: true,
  7565. configurable: true
  7566. });
  7567. Object.defineProperty(Tools, "WarningLogLevel", {
  7568. get: function () {
  7569. return Tools._WarningLogLevel;
  7570. },
  7571. enumerable: true,
  7572. configurable: true
  7573. });
  7574. Object.defineProperty(Tools, "ErrorLogLevel", {
  7575. get: function () {
  7576. return Tools._ErrorLogLevel;
  7577. },
  7578. enumerable: true,
  7579. configurable: true
  7580. });
  7581. Object.defineProperty(Tools, "AllLogLevel", {
  7582. get: function () {
  7583. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7584. },
  7585. enumerable: true,
  7586. configurable: true
  7587. });
  7588. Tools._AddLogEntry = function (entry) {
  7589. Tools._LogCache = entry + Tools._LogCache;
  7590. if (Tools.OnNewCacheEntry) {
  7591. Tools.OnNewCacheEntry(entry);
  7592. }
  7593. };
  7594. Tools._FormatMessage = function (message) {
  7595. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7596. var date = new Date();
  7597. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7598. };
  7599. Tools._LogDisabled = function (message) {
  7600. // nothing to do
  7601. };
  7602. Tools._LogEnabled = function (message) {
  7603. var formattedMessage = Tools._FormatMessage(message);
  7604. console.log("BJS - " + formattedMessage);
  7605. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7606. Tools._AddLogEntry(entry);
  7607. };
  7608. Tools._WarnDisabled = function (message) {
  7609. // nothing to do
  7610. };
  7611. Tools._WarnEnabled = function (message) {
  7612. var formattedMessage = Tools._FormatMessage(message);
  7613. console.warn("BJS - " + formattedMessage);
  7614. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7615. Tools._AddLogEntry(entry);
  7616. };
  7617. Tools._ErrorDisabled = function (message) {
  7618. // nothing to do
  7619. };
  7620. Tools._ErrorEnabled = function (message) {
  7621. Tools.errorsCount++;
  7622. var formattedMessage = Tools._FormatMessage(message);
  7623. console.error("BJS - " + formattedMessage);
  7624. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7625. Tools._AddLogEntry(entry);
  7626. };
  7627. Object.defineProperty(Tools, "LogCache", {
  7628. get: function () {
  7629. return Tools._LogCache;
  7630. },
  7631. enumerable: true,
  7632. configurable: true
  7633. });
  7634. Tools.ClearLogCache = function () {
  7635. Tools._LogCache = "";
  7636. Tools.errorsCount = 0;
  7637. };
  7638. Object.defineProperty(Tools, "LogLevels", {
  7639. set: function (level) {
  7640. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7641. Tools.Log = Tools._LogEnabled;
  7642. }
  7643. else {
  7644. Tools.Log = Tools._LogDisabled;
  7645. }
  7646. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7647. Tools.Warn = Tools._WarnEnabled;
  7648. }
  7649. else {
  7650. Tools.Warn = Tools._WarnDisabled;
  7651. }
  7652. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7653. Tools.Error = Tools._ErrorEnabled;
  7654. }
  7655. else {
  7656. Tools.Error = Tools._ErrorDisabled;
  7657. }
  7658. },
  7659. enumerable: true,
  7660. configurable: true
  7661. });
  7662. Tools.IsWindowObjectExist = function () {
  7663. return (typeof window) !== "undefined";
  7664. };
  7665. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  7666. get: function () {
  7667. return Tools._PerformanceNoneLogLevel;
  7668. },
  7669. enumerable: true,
  7670. configurable: true
  7671. });
  7672. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  7673. get: function () {
  7674. return Tools._PerformanceUserMarkLogLevel;
  7675. },
  7676. enumerable: true,
  7677. configurable: true
  7678. });
  7679. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  7680. get: function () {
  7681. return Tools._PerformanceConsoleLogLevel;
  7682. },
  7683. enumerable: true,
  7684. configurable: true
  7685. });
  7686. Object.defineProperty(Tools, "PerformanceLogLevel", {
  7687. set: function (level) {
  7688. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  7689. Tools.StartPerformanceCounter = Tools._StartUserMark;
  7690. Tools.EndPerformanceCounter = Tools._EndUserMark;
  7691. return;
  7692. }
  7693. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  7694. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  7695. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  7696. return;
  7697. }
  7698. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7699. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7700. },
  7701. enumerable: true,
  7702. configurable: true
  7703. });
  7704. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  7705. };
  7706. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  7707. };
  7708. Tools._StartUserMark = function (counterName, condition) {
  7709. if (condition === void 0) { condition = true; }
  7710. if (!Tools._performance) {
  7711. if (!Tools.IsWindowObjectExist()) {
  7712. return;
  7713. }
  7714. Tools._performance = window.performance;
  7715. }
  7716. if (!condition || !Tools._performance.mark) {
  7717. return;
  7718. }
  7719. Tools._performance.mark(counterName + "-Begin");
  7720. };
  7721. Tools._EndUserMark = function (counterName, condition) {
  7722. if (condition === void 0) { condition = true; }
  7723. if (!condition || !Tools._performance.mark) {
  7724. return;
  7725. }
  7726. Tools._performance.mark(counterName + "-End");
  7727. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  7728. };
  7729. Tools._StartPerformanceConsole = function (counterName, condition) {
  7730. if (condition === void 0) { condition = true; }
  7731. if (!condition) {
  7732. return;
  7733. }
  7734. Tools._StartUserMark(counterName, condition);
  7735. if (console.time) {
  7736. console.time(counterName);
  7737. }
  7738. };
  7739. Tools._EndPerformanceConsole = function (counterName, condition) {
  7740. if (condition === void 0) { condition = true; }
  7741. if (!condition) {
  7742. return;
  7743. }
  7744. Tools._EndUserMark(counterName, condition);
  7745. if (console.time) {
  7746. console.timeEnd(counterName);
  7747. }
  7748. };
  7749. Object.defineProperty(Tools, "Now", {
  7750. get: function () {
  7751. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  7752. return window.performance.now();
  7753. }
  7754. return new Date().getTime();
  7755. },
  7756. enumerable: true,
  7757. configurable: true
  7758. });
  7759. /**
  7760. * This method will return the name of the class used to create the instance of the given object.
  7761. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  7762. * @param object the object to get the class name from
  7763. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  7764. */
  7765. Tools.GetClassName = function (object, isType) {
  7766. if (isType === void 0) { isType = false; }
  7767. var name = null;
  7768. if (!isType && object.getClassName) {
  7769. name = object.getClassName();
  7770. }
  7771. else {
  7772. if (object instanceof Object) {
  7773. var classObj = isType ? object : Object.getPrototypeOf(object);
  7774. name = classObj.constructor["__bjsclassName__"];
  7775. }
  7776. if (!name) {
  7777. name = typeof object;
  7778. }
  7779. }
  7780. return name;
  7781. };
  7782. Tools.First = function (array, predicate) {
  7783. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7784. var el = array_1[_i];
  7785. if (predicate(el)) {
  7786. return el;
  7787. }
  7788. }
  7789. return null;
  7790. };
  7791. /**
  7792. * This method will return the name of the full name of the class, including its owning module (if any).
  7793. * 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).
  7794. * @param object the object to get the class name from
  7795. * @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.
  7796. */
  7797. Tools.getFullClassName = function (object, isType) {
  7798. if (isType === void 0) { isType = false; }
  7799. var className = null;
  7800. var moduleName = null;
  7801. if (!isType && object.getClassName) {
  7802. className = object.getClassName();
  7803. }
  7804. else {
  7805. if (object instanceof Object) {
  7806. var classObj = isType ? object : Object.getPrototypeOf(object);
  7807. className = classObj.constructor["__bjsclassName__"];
  7808. moduleName = classObj.constructor["__bjsmoduleName__"];
  7809. }
  7810. if (!className) {
  7811. className = typeof object;
  7812. }
  7813. }
  7814. if (!className) {
  7815. return null;
  7816. }
  7817. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7818. };
  7819. /**
  7820. * 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.
  7821. * @param array
  7822. */
  7823. Tools.arrayOrStringFeeder = function (array) {
  7824. return function (index) {
  7825. if (index >= array.length) {
  7826. return null;
  7827. }
  7828. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7829. if (val && val.getHashCode) {
  7830. val = val.getHashCode();
  7831. }
  7832. if (typeof val === "string") {
  7833. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7834. }
  7835. return val;
  7836. };
  7837. };
  7838. /**
  7839. * Compute the hashCode of a stream of number
  7840. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7841. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7842. * @return the hash code computed
  7843. */
  7844. Tools.hashCodeFromStream = function (feeder) {
  7845. // Based from here: http://stackoverflow.com/a/7616484/802124
  7846. var hash = 0;
  7847. var index = 0;
  7848. var chr = feeder(index++);
  7849. while (chr != null) {
  7850. hash = ((hash << 5) - hash) + chr;
  7851. hash |= 0; // Convert to 32bit integer
  7852. chr = feeder(index++);
  7853. }
  7854. return hash;
  7855. };
  7856. Tools.BaseUrl = "";
  7857. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7858. /**
  7859. * Default behaviour for cors in the application.
  7860. * It can be a string if the expected behavior is identical in the entire app.
  7861. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7862. */
  7863. Tools.CorsBehavior = "anonymous";
  7864. Tools.UseFallbackTexture = true;
  7865. /**
  7866. * Use this object to register external classes like custom textures or material
  7867. * to allow the laoders to instantiate them
  7868. */
  7869. Tools.RegisteredExternalClasses = {};
  7870. // Used in case of a texture loading problem
  7871. 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";
  7872. Tools.PreprocessUrl = function (url) {
  7873. return url;
  7874. };
  7875. // Logs
  7876. Tools._NoneLogLevel = 0;
  7877. Tools._MessageLogLevel = 1;
  7878. Tools._WarningLogLevel = 2;
  7879. Tools._ErrorLogLevel = 4;
  7880. Tools._LogCache = "";
  7881. Tools.errorsCount = 0;
  7882. Tools.Log = Tools._LogEnabled;
  7883. Tools.Warn = Tools._WarnEnabled;
  7884. Tools.Error = Tools._ErrorEnabled;
  7885. // Performances
  7886. Tools._PerformanceNoneLogLevel = 0;
  7887. Tools._PerformanceUserMarkLogLevel = 1;
  7888. Tools._PerformanceConsoleLogLevel = 2;
  7889. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7890. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7891. return Tools;
  7892. }());
  7893. BABYLON.Tools = Tools;
  7894. /**
  7895. * This class is used to track a performance counter which is number based.
  7896. * The user has access to many properties which give statistics of different nature
  7897. *
  7898. * The implementer can track two kinds of Performance Counter: time and count
  7899. * 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.
  7900. * 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.
  7901. */
  7902. var PerfCounter = /** @class */ (function () {
  7903. function PerfCounter() {
  7904. this._startMonitoringTime = 0;
  7905. this._min = 0;
  7906. this._max = 0;
  7907. this._average = 0;
  7908. this._lastSecAverage = 0;
  7909. this._current = 0;
  7910. this._totalValueCount = 0;
  7911. this._totalAccumulated = 0;
  7912. this._lastSecAccumulated = 0;
  7913. this._lastSecTime = 0;
  7914. this._lastSecValueCount = 0;
  7915. }
  7916. Object.defineProperty(PerfCounter.prototype, "min", {
  7917. /**
  7918. * Returns the smallest value ever
  7919. */
  7920. get: function () {
  7921. return this._min;
  7922. },
  7923. enumerable: true,
  7924. configurable: true
  7925. });
  7926. Object.defineProperty(PerfCounter.prototype, "max", {
  7927. /**
  7928. * Returns the biggest value ever
  7929. */
  7930. get: function () {
  7931. return this._max;
  7932. },
  7933. enumerable: true,
  7934. configurable: true
  7935. });
  7936. Object.defineProperty(PerfCounter.prototype, "average", {
  7937. /**
  7938. * Returns the average value since the performance counter is running
  7939. */
  7940. get: function () {
  7941. return this._average;
  7942. },
  7943. enumerable: true,
  7944. configurable: true
  7945. });
  7946. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7947. /**
  7948. * Returns the average value of the last second the counter was monitored
  7949. */
  7950. get: function () {
  7951. return this._lastSecAverage;
  7952. },
  7953. enumerable: true,
  7954. configurable: true
  7955. });
  7956. Object.defineProperty(PerfCounter.prototype, "current", {
  7957. /**
  7958. * Returns the current value
  7959. */
  7960. get: function () {
  7961. return this._current;
  7962. },
  7963. enumerable: true,
  7964. configurable: true
  7965. });
  7966. Object.defineProperty(PerfCounter.prototype, "total", {
  7967. get: function () {
  7968. return this._totalAccumulated;
  7969. },
  7970. enumerable: true,
  7971. configurable: true
  7972. });
  7973. Object.defineProperty(PerfCounter.prototype, "count", {
  7974. get: function () {
  7975. return this._totalValueCount;
  7976. },
  7977. enumerable: true,
  7978. configurable: true
  7979. });
  7980. /**
  7981. * Call this method to start monitoring a new frame.
  7982. * 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.
  7983. */
  7984. PerfCounter.prototype.fetchNewFrame = function () {
  7985. this._totalValueCount++;
  7986. this._current = 0;
  7987. this._lastSecValueCount++;
  7988. };
  7989. /**
  7990. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7991. * @param newCount the count value to add to the monitored count
  7992. * @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.
  7993. */
  7994. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7995. if (!PerfCounter.Enabled) {
  7996. return;
  7997. }
  7998. this._current += newCount;
  7999. if (fetchResult) {
  8000. this._fetchResult();
  8001. }
  8002. };
  8003. /**
  8004. * Start monitoring this performance counter
  8005. */
  8006. PerfCounter.prototype.beginMonitoring = function () {
  8007. if (!PerfCounter.Enabled) {
  8008. return;
  8009. }
  8010. this._startMonitoringTime = Tools.Now;
  8011. };
  8012. /**
  8013. * Compute the time lapsed since the previous beginMonitoring() call.
  8014. * @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
  8015. */
  8016. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8017. if (newFrame === void 0) { newFrame = true; }
  8018. if (!PerfCounter.Enabled) {
  8019. return;
  8020. }
  8021. if (newFrame) {
  8022. this.fetchNewFrame();
  8023. }
  8024. var currentTime = Tools.Now;
  8025. this._current = currentTime - this._startMonitoringTime;
  8026. if (newFrame) {
  8027. this._fetchResult();
  8028. }
  8029. };
  8030. PerfCounter.prototype._fetchResult = function () {
  8031. this._totalAccumulated += this._current;
  8032. this._lastSecAccumulated += this._current;
  8033. // Min/Max update
  8034. this._min = Math.min(this._min, this._current);
  8035. this._max = Math.max(this._max, this._current);
  8036. this._average = this._totalAccumulated / this._totalValueCount;
  8037. // Reset last sec?
  8038. var now = Tools.Now;
  8039. if ((now - this._lastSecTime) > 1000) {
  8040. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8041. this._lastSecTime = now;
  8042. this._lastSecAccumulated = 0;
  8043. this._lastSecValueCount = 0;
  8044. }
  8045. };
  8046. PerfCounter.Enabled = true;
  8047. return PerfCounter;
  8048. }());
  8049. BABYLON.PerfCounter = PerfCounter;
  8050. /**
  8051. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8052. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8053. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8054. * @param name The name of the class, case should be preserved
  8055. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8056. */
  8057. function className(name, module) {
  8058. return function (target) {
  8059. target["__bjsclassName__"] = name;
  8060. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8061. };
  8062. }
  8063. BABYLON.className = className;
  8064. /**
  8065. * An implementation of a loop for asynchronous functions.
  8066. */
  8067. var AsyncLoop = /** @class */ (function () {
  8068. /**
  8069. * Constroctor.
  8070. * @param iterations the number of iterations.
  8071. * @param _fn the function to run each iteration
  8072. * @param _successCallback the callback that will be called upon succesful execution
  8073. * @param offset starting offset.
  8074. */
  8075. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8076. if (offset === void 0) { offset = 0; }
  8077. this.iterations = iterations;
  8078. this._fn = _fn;
  8079. this._successCallback = _successCallback;
  8080. this.index = offset - 1;
  8081. this._done = false;
  8082. }
  8083. /**
  8084. * Execute the next iteration. Must be called after the last iteration was finished.
  8085. */
  8086. AsyncLoop.prototype.executeNext = function () {
  8087. if (!this._done) {
  8088. if (this.index + 1 < this.iterations) {
  8089. ++this.index;
  8090. this._fn(this);
  8091. }
  8092. else {
  8093. this.breakLoop();
  8094. }
  8095. }
  8096. };
  8097. /**
  8098. * Break the loop and run the success callback.
  8099. */
  8100. AsyncLoop.prototype.breakLoop = function () {
  8101. this._done = true;
  8102. this._successCallback();
  8103. };
  8104. /**
  8105. * Helper function
  8106. */
  8107. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8108. if (offset === void 0) { offset = 0; }
  8109. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8110. loop.executeNext();
  8111. return loop;
  8112. };
  8113. /**
  8114. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8115. * @param iterations total number of iterations
  8116. * @param syncedIterations number of synchronous iterations in each async iteration.
  8117. * @param fn the function to call each iteration.
  8118. * @param callback a success call back that will be called when iterating stops.
  8119. * @param breakFunction a break condition (optional)
  8120. * @param timeout timeout settings for the setTimeout function. default - 0.
  8121. * @constructor
  8122. */
  8123. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8124. if (timeout === void 0) { timeout = 0; }
  8125. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8126. if (breakFunction && breakFunction())
  8127. loop.breakLoop();
  8128. else {
  8129. setTimeout(function () {
  8130. for (var i = 0; i < syncedIterations; ++i) {
  8131. var iteration = (loop.index * syncedIterations) + i;
  8132. if (iteration >= iterations)
  8133. break;
  8134. fn(iteration);
  8135. if (breakFunction && breakFunction()) {
  8136. loop.breakLoop();
  8137. break;
  8138. }
  8139. }
  8140. loop.executeNext();
  8141. }, timeout);
  8142. }
  8143. }, callback);
  8144. };
  8145. return AsyncLoop;
  8146. }());
  8147. BABYLON.AsyncLoop = AsyncLoop;
  8148. })(BABYLON || (BABYLON = {}));
  8149. //# sourceMappingURL=babylon.tools.js.map
  8150. var BABYLON;
  8151. (function (BABYLON) {
  8152. var _AlphaState = /** @class */ (function () {
  8153. /**
  8154. * Initializes the state.
  8155. */
  8156. function _AlphaState() {
  8157. this._isAlphaBlendDirty = false;
  8158. this._isBlendFunctionParametersDirty = false;
  8159. this._isBlendEquationParametersDirty = false;
  8160. this._isBlendConstantsDirty = false;
  8161. this._alphaBlend = false;
  8162. this._blendFunctionParameters = new Array(4);
  8163. this._blendEquationParameters = new Array(2);
  8164. this._blendConstants = new Array(4);
  8165. this.reset();
  8166. }
  8167. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8168. get: function () {
  8169. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8170. },
  8171. enumerable: true,
  8172. configurable: true
  8173. });
  8174. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8175. get: function () {
  8176. return this._alphaBlend;
  8177. },
  8178. set: function (value) {
  8179. if (this._alphaBlend === value) {
  8180. return;
  8181. }
  8182. this._alphaBlend = value;
  8183. this._isAlphaBlendDirty = true;
  8184. },
  8185. enumerable: true,
  8186. configurable: true
  8187. });
  8188. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8189. if (this._blendConstants[0] === r &&
  8190. this._blendConstants[1] === g &&
  8191. this._blendConstants[2] === b &&
  8192. this._blendConstants[3] === a) {
  8193. return;
  8194. }
  8195. this._blendConstants[0] = r;
  8196. this._blendConstants[1] = g;
  8197. this._blendConstants[2] = b;
  8198. this._blendConstants[3] = a;
  8199. this._isBlendConstantsDirty = true;
  8200. };
  8201. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8202. if (this._blendFunctionParameters[0] === value0 &&
  8203. this._blendFunctionParameters[1] === value1 &&
  8204. this._blendFunctionParameters[2] === value2 &&
  8205. this._blendFunctionParameters[3] === value3) {
  8206. return;
  8207. }
  8208. this._blendFunctionParameters[0] = value0;
  8209. this._blendFunctionParameters[1] = value1;
  8210. this._blendFunctionParameters[2] = value2;
  8211. this._blendFunctionParameters[3] = value3;
  8212. this._isBlendFunctionParametersDirty = true;
  8213. };
  8214. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8215. if (this._blendEquationParameters[0] === rgb &&
  8216. this._blendEquationParameters[1] === alpha) {
  8217. return;
  8218. }
  8219. this._blendEquationParameters[0] = rgb;
  8220. this._blendEquationParameters[1] = alpha;
  8221. this._isBlendEquationParametersDirty = true;
  8222. };
  8223. _AlphaState.prototype.reset = function () {
  8224. this._alphaBlend = false;
  8225. this._blendFunctionParameters[0] = null;
  8226. this._blendFunctionParameters[1] = null;
  8227. this._blendFunctionParameters[2] = null;
  8228. this._blendFunctionParameters[3] = null;
  8229. this._blendEquationParameters[0] = null;
  8230. this._blendEquationParameters[1] = null;
  8231. this._blendConstants[0] = null;
  8232. this._blendConstants[1] = null;
  8233. this._blendConstants[2] = null;
  8234. this._blendConstants[3] = null;
  8235. this._isAlphaBlendDirty = true;
  8236. this._isBlendFunctionParametersDirty = false;
  8237. this._isBlendEquationParametersDirty = false;
  8238. this._isBlendConstantsDirty = false;
  8239. };
  8240. _AlphaState.prototype.apply = function (gl) {
  8241. if (!this.isDirty) {
  8242. return;
  8243. }
  8244. // Alpha blend
  8245. if (this._isAlphaBlendDirty) {
  8246. if (this._alphaBlend) {
  8247. gl.enable(gl.BLEND);
  8248. }
  8249. else {
  8250. gl.disable(gl.BLEND);
  8251. }
  8252. this._isAlphaBlendDirty = false;
  8253. }
  8254. // Alpha function
  8255. if (this._isBlendFunctionParametersDirty) {
  8256. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8257. this._isBlendFunctionParametersDirty = false;
  8258. }
  8259. // Alpha equation
  8260. if (this._isBlendEquationParametersDirty) {
  8261. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8262. this._isBlendEquationParametersDirty = false;
  8263. }
  8264. // Constants
  8265. if (this._isBlendConstantsDirty) {
  8266. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8267. this._isBlendConstantsDirty = false;
  8268. }
  8269. };
  8270. return _AlphaState;
  8271. }());
  8272. BABYLON._AlphaState = _AlphaState;
  8273. })(BABYLON || (BABYLON = {}));
  8274. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8275. var BABYLON;
  8276. (function (BABYLON) {
  8277. var _DepthCullingState = /** @class */ (function () {
  8278. /**
  8279. * Initializes the state.
  8280. */
  8281. function _DepthCullingState() {
  8282. this._isDepthTestDirty = false;
  8283. this._isDepthMaskDirty = false;
  8284. this._isDepthFuncDirty = false;
  8285. this._isCullFaceDirty = false;
  8286. this._isCullDirty = false;
  8287. this._isZOffsetDirty = false;
  8288. this._isFrontFaceDirty = false;
  8289. this.reset();
  8290. }
  8291. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8292. get: function () {
  8293. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8294. },
  8295. enumerable: true,
  8296. configurable: true
  8297. });
  8298. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8299. get: function () {
  8300. return this._zOffset;
  8301. },
  8302. set: function (value) {
  8303. if (this._zOffset === value) {
  8304. return;
  8305. }
  8306. this._zOffset = value;
  8307. this._isZOffsetDirty = true;
  8308. },
  8309. enumerable: true,
  8310. configurable: true
  8311. });
  8312. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8313. get: function () {
  8314. return this._cullFace;
  8315. },
  8316. set: function (value) {
  8317. if (this._cullFace === value) {
  8318. return;
  8319. }
  8320. this._cullFace = value;
  8321. this._isCullFaceDirty = true;
  8322. },
  8323. enumerable: true,
  8324. configurable: true
  8325. });
  8326. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8327. get: function () {
  8328. return this._cull;
  8329. },
  8330. set: function (value) {
  8331. if (this._cull === value) {
  8332. return;
  8333. }
  8334. this._cull = value;
  8335. this._isCullDirty = true;
  8336. },
  8337. enumerable: true,
  8338. configurable: true
  8339. });
  8340. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8341. get: function () {
  8342. return this._depthFunc;
  8343. },
  8344. set: function (value) {
  8345. if (this._depthFunc === value) {
  8346. return;
  8347. }
  8348. this._depthFunc = value;
  8349. this._isDepthFuncDirty = true;
  8350. },
  8351. enumerable: true,
  8352. configurable: true
  8353. });
  8354. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8355. get: function () {
  8356. return this._depthMask;
  8357. },
  8358. set: function (value) {
  8359. if (this._depthMask === value) {
  8360. return;
  8361. }
  8362. this._depthMask = value;
  8363. this._isDepthMaskDirty = true;
  8364. },
  8365. enumerable: true,
  8366. configurable: true
  8367. });
  8368. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8369. get: function () {
  8370. return this._depthTest;
  8371. },
  8372. set: function (value) {
  8373. if (this._depthTest === value) {
  8374. return;
  8375. }
  8376. this._depthTest = value;
  8377. this._isDepthTestDirty = true;
  8378. },
  8379. enumerable: true,
  8380. configurable: true
  8381. });
  8382. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8383. get: function () {
  8384. return this._frontFace;
  8385. },
  8386. set: function (value) {
  8387. if (this._frontFace === value) {
  8388. return;
  8389. }
  8390. this._frontFace = value;
  8391. this._isFrontFaceDirty = true;
  8392. },
  8393. enumerable: true,
  8394. configurable: true
  8395. });
  8396. _DepthCullingState.prototype.reset = function () {
  8397. this._depthMask = true;
  8398. this._depthTest = true;
  8399. this._depthFunc = null;
  8400. this._cullFace = null;
  8401. this._cull = null;
  8402. this._zOffset = 0;
  8403. this._frontFace = null;
  8404. this._isDepthTestDirty = true;
  8405. this._isDepthMaskDirty = true;
  8406. this._isDepthFuncDirty = false;
  8407. this._isCullFaceDirty = false;
  8408. this._isCullDirty = false;
  8409. this._isZOffsetDirty = false;
  8410. this._isFrontFaceDirty = false;
  8411. };
  8412. _DepthCullingState.prototype.apply = function (gl) {
  8413. if (!this.isDirty) {
  8414. return;
  8415. }
  8416. // Cull
  8417. if (this._isCullDirty) {
  8418. if (this.cull) {
  8419. gl.enable(gl.CULL_FACE);
  8420. }
  8421. else {
  8422. gl.disable(gl.CULL_FACE);
  8423. }
  8424. this._isCullDirty = false;
  8425. }
  8426. // Cull face
  8427. if (this._isCullFaceDirty) {
  8428. gl.cullFace(this.cullFace);
  8429. this._isCullFaceDirty = false;
  8430. }
  8431. // Depth mask
  8432. if (this._isDepthMaskDirty) {
  8433. gl.depthMask(this.depthMask);
  8434. this._isDepthMaskDirty = false;
  8435. }
  8436. // Depth test
  8437. if (this._isDepthTestDirty) {
  8438. if (this.depthTest) {
  8439. gl.enable(gl.DEPTH_TEST);
  8440. }
  8441. else {
  8442. gl.disable(gl.DEPTH_TEST);
  8443. }
  8444. this._isDepthTestDirty = false;
  8445. }
  8446. // Depth func
  8447. if (this._isDepthFuncDirty) {
  8448. gl.depthFunc(this.depthFunc);
  8449. this._isDepthFuncDirty = false;
  8450. }
  8451. // zOffset
  8452. if (this._isZOffsetDirty) {
  8453. if (this.zOffset) {
  8454. gl.enable(gl.POLYGON_OFFSET_FILL);
  8455. gl.polygonOffset(this.zOffset, 0);
  8456. }
  8457. else {
  8458. gl.disable(gl.POLYGON_OFFSET_FILL);
  8459. }
  8460. this._isZOffsetDirty = false;
  8461. }
  8462. // Front face
  8463. if (this._isFrontFaceDirty) {
  8464. gl.frontFace(this.frontFace);
  8465. this._isFrontFaceDirty = false;
  8466. }
  8467. };
  8468. return _DepthCullingState;
  8469. }());
  8470. BABYLON._DepthCullingState = _DepthCullingState;
  8471. })(BABYLON || (BABYLON = {}));
  8472. //# sourceMappingURL=babylon.depthCullingState.js.map
  8473. var BABYLON;
  8474. (function (BABYLON) {
  8475. var _StencilState = /** @class */ (function () {
  8476. function _StencilState() {
  8477. this._isStencilTestDirty = false;
  8478. this._isStencilMaskDirty = false;
  8479. this._isStencilFuncDirty = false;
  8480. this._isStencilOpDirty = false;
  8481. this.reset();
  8482. }
  8483. Object.defineProperty(_StencilState.prototype, "isDirty", {
  8484. get: function () {
  8485. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  8486. },
  8487. enumerable: true,
  8488. configurable: true
  8489. });
  8490. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  8491. get: function () {
  8492. return this._stencilFunc;
  8493. },
  8494. set: function (value) {
  8495. if (this._stencilFunc === value) {
  8496. return;
  8497. }
  8498. this._stencilFunc = value;
  8499. this._isStencilFuncDirty = true;
  8500. },
  8501. enumerable: true,
  8502. configurable: true
  8503. });
  8504. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  8505. get: function () {
  8506. return this._stencilFuncRef;
  8507. },
  8508. set: function (value) {
  8509. if (this._stencilFuncRef === value) {
  8510. return;
  8511. }
  8512. this._stencilFuncRef = value;
  8513. this._isStencilFuncDirty = true;
  8514. },
  8515. enumerable: true,
  8516. configurable: true
  8517. });
  8518. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  8519. get: function () {
  8520. return this._stencilFuncMask;
  8521. },
  8522. set: function (value) {
  8523. if (this._stencilFuncMask === value) {
  8524. return;
  8525. }
  8526. this._stencilFuncMask = value;
  8527. this._isStencilFuncDirty = true;
  8528. },
  8529. enumerable: true,
  8530. configurable: true
  8531. });
  8532. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  8533. get: function () {
  8534. return this._stencilOpStencilFail;
  8535. },
  8536. set: function (value) {
  8537. if (this._stencilOpStencilFail === value) {
  8538. return;
  8539. }
  8540. this._stencilOpStencilFail = value;
  8541. this._isStencilOpDirty = true;
  8542. },
  8543. enumerable: true,
  8544. configurable: true
  8545. });
  8546. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  8547. get: function () {
  8548. return this._stencilOpDepthFail;
  8549. },
  8550. set: function (value) {
  8551. if (this._stencilOpDepthFail === value) {
  8552. return;
  8553. }
  8554. this._stencilOpDepthFail = value;
  8555. this._isStencilOpDirty = true;
  8556. },
  8557. enumerable: true,
  8558. configurable: true
  8559. });
  8560. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  8561. get: function () {
  8562. return this._stencilOpStencilDepthPass;
  8563. },
  8564. set: function (value) {
  8565. if (this._stencilOpStencilDepthPass === value) {
  8566. return;
  8567. }
  8568. this._stencilOpStencilDepthPass = value;
  8569. this._isStencilOpDirty = true;
  8570. },
  8571. enumerable: true,
  8572. configurable: true
  8573. });
  8574. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  8575. get: function () {
  8576. return this._stencilMask;
  8577. },
  8578. set: function (value) {
  8579. if (this._stencilMask === value) {
  8580. return;
  8581. }
  8582. this._stencilMask = value;
  8583. this._isStencilMaskDirty = true;
  8584. },
  8585. enumerable: true,
  8586. configurable: true
  8587. });
  8588. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  8589. get: function () {
  8590. return this._stencilTest;
  8591. },
  8592. set: function (value) {
  8593. if (this._stencilTest === value) {
  8594. return;
  8595. }
  8596. this._stencilTest = value;
  8597. this._isStencilTestDirty = true;
  8598. },
  8599. enumerable: true,
  8600. configurable: true
  8601. });
  8602. _StencilState.prototype.reset = function () {
  8603. this._stencilTest = false;
  8604. this._stencilMask = 0xFF;
  8605. this._stencilFunc = BABYLON.Engine.ALWAYS;
  8606. this._stencilFuncRef = 1;
  8607. this._stencilFuncMask = 0xFF;
  8608. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  8609. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  8610. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  8611. this._isStencilTestDirty = true;
  8612. this._isStencilMaskDirty = true;
  8613. this._isStencilFuncDirty = true;
  8614. this._isStencilOpDirty = true;
  8615. };
  8616. _StencilState.prototype.apply = function (gl) {
  8617. if (!this.isDirty) {
  8618. return;
  8619. }
  8620. // Stencil test
  8621. if (this._isStencilTestDirty) {
  8622. if (this.stencilTest) {
  8623. gl.enable(gl.STENCIL_TEST);
  8624. }
  8625. else {
  8626. gl.disable(gl.STENCIL_TEST);
  8627. }
  8628. this._isStencilTestDirty = false;
  8629. }
  8630. // Stencil mask
  8631. if (this._isStencilMaskDirty) {
  8632. gl.stencilMask(this.stencilMask);
  8633. this._isStencilMaskDirty = false;
  8634. }
  8635. // Stencil func
  8636. if (this._isStencilFuncDirty) {
  8637. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  8638. this._isStencilFuncDirty = false;
  8639. }
  8640. // Stencil op
  8641. if (this._isStencilOpDirty) {
  8642. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  8643. this._isStencilOpDirty = false;
  8644. }
  8645. };
  8646. return _StencilState;
  8647. }());
  8648. BABYLON._StencilState = _StencilState;
  8649. })(BABYLON || (BABYLON = {}));
  8650. //# sourceMappingURL=babylon.stencilState.js.map
  8651. var BABYLON;
  8652. (function (BABYLON) {
  8653. var compileShader = function (gl, source, type, defines, shaderVersion) {
  8654. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  8655. };
  8656. var compileRawShader = function (gl, source, type) {
  8657. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  8658. gl.shaderSource(shader, source);
  8659. gl.compileShader(shader);
  8660. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8661. var log = gl.getShaderInfoLog(shader);
  8662. if (log) {
  8663. throw new Error(log);
  8664. }
  8665. }
  8666. if (!shader) {
  8667. throw new Error("Something went wrong while compile the shader.");
  8668. }
  8669. return shader;
  8670. };
  8671. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  8672. var magFilter = gl.NEAREST;
  8673. var minFilter = gl.NEAREST;
  8674. switch (samplingMode) {
  8675. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  8676. magFilter = gl.LINEAR;
  8677. if (generateMipMaps) {
  8678. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8679. }
  8680. else {
  8681. minFilter = gl.LINEAR;
  8682. }
  8683. break;
  8684. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  8685. magFilter = gl.LINEAR;
  8686. if (generateMipMaps) {
  8687. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8688. }
  8689. else {
  8690. minFilter = gl.LINEAR;
  8691. }
  8692. break;
  8693. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  8694. magFilter = gl.NEAREST;
  8695. if (generateMipMaps) {
  8696. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8697. }
  8698. else {
  8699. minFilter = gl.NEAREST;
  8700. }
  8701. break;
  8702. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  8703. magFilter = gl.NEAREST;
  8704. if (generateMipMaps) {
  8705. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8706. }
  8707. else {
  8708. minFilter = gl.NEAREST;
  8709. }
  8710. break;
  8711. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  8712. magFilter = gl.NEAREST;
  8713. if (generateMipMaps) {
  8714. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8715. }
  8716. else {
  8717. minFilter = gl.LINEAR;
  8718. }
  8719. break;
  8720. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  8721. magFilter = gl.NEAREST;
  8722. if (generateMipMaps) {
  8723. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8724. }
  8725. else {
  8726. minFilter = gl.LINEAR;
  8727. }
  8728. break;
  8729. case BABYLON.Texture.NEAREST_LINEAR:
  8730. magFilter = gl.NEAREST;
  8731. minFilter = gl.LINEAR;
  8732. break;
  8733. case BABYLON.Texture.NEAREST_NEAREST:
  8734. magFilter = gl.NEAREST;
  8735. minFilter = gl.NEAREST;
  8736. break;
  8737. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  8738. magFilter = gl.LINEAR;
  8739. if (generateMipMaps) {
  8740. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8741. }
  8742. else {
  8743. minFilter = gl.NEAREST;
  8744. }
  8745. break;
  8746. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  8747. magFilter = gl.LINEAR;
  8748. if (generateMipMaps) {
  8749. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8750. }
  8751. else {
  8752. minFilter = gl.NEAREST;
  8753. }
  8754. break;
  8755. case BABYLON.Texture.LINEAR_LINEAR:
  8756. magFilter = gl.LINEAR;
  8757. minFilter = gl.LINEAR;
  8758. break;
  8759. case BABYLON.Texture.LINEAR_NEAREST:
  8760. magFilter = gl.LINEAR;
  8761. minFilter = gl.NEAREST;
  8762. break;
  8763. }
  8764. return {
  8765. min: minFilter,
  8766. mag: magFilter
  8767. };
  8768. };
  8769. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  8770. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  8771. var img;
  8772. var onload = function () {
  8773. loadedImages[index] = img;
  8774. loadedImages._internalCount++;
  8775. if (scene) {
  8776. scene._removePendingData(img);
  8777. }
  8778. if (loadedImages._internalCount === 6) {
  8779. onfinish(loadedImages);
  8780. }
  8781. };
  8782. var onerror = function (message, exception) {
  8783. if (scene) {
  8784. scene._removePendingData(img);
  8785. }
  8786. if (onErrorCallBack) {
  8787. onErrorCallBack(message, exception);
  8788. }
  8789. };
  8790. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  8791. if (scene) {
  8792. scene._addPendingData(img);
  8793. }
  8794. };
  8795. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  8796. if (onError === void 0) { onError = null; }
  8797. var loadedImages = [];
  8798. loadedImages._internalCount = 0;
  8799. for (var index = 0; index < 6; index++) {
  8800. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  8801. }
  8802. };
  8803. var BufferPointer = /** @class */ (function () {
  8804. function BufferPointer() {
  8805. }
  8806. return BufferPointer;
  8807. }());
  8808. var InstancingAttributeInfo = /** @class */ (function () {
  8809. function InstancingAttributeInfo() {
  8810. }
  8811. return InstancingAttributeInfo;
  8812. }());
  8813. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  8814. /**
  8815. * Define options used to create a render target texture
  8816. */
  8817. var RenderTargetCreationOptions = /** @class */ (function () {
  8818. function RenderTargetCreationOptions() {
  8819. }
  8820. return RenderTargetCreationOptions;
  8821. }());
  8822. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  8823. /**
  8824. * Regroup several parameters relative to the browser in use
  8825. */
  8826. var EngineCapabilities = /** @class */ (function () {
  8827. function EngineCapabilities() {
  8828. }
  8829. return EngineCapabilities;
  8830. }());
  8831. BABYLON.EngineCapabilities = EngineCapabilities;
  8832. /**
  8833. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  8834. */
  8835. var Engine = /** @class */ (function () {
  8836. /**
  8837. * @constructor
  8838. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  8839. * @param {boolean} [antialias] - enable antialias
  8840. * @param options - further options to be sent to the getContext function
  8841. */
  8842. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  8843. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  8844. var _this = this;
  8845. // Public members
  8846. this.forcePOTTextures = false;
  8847. this.isFullscreen = false;
  8848. this.isPointerLock = false;
  8849. this.cullBackFaces = true;
  8850. this.renderEvenInBackground = true;
  8851. this.preventCacheWipeBetweenFrames = false;
  8852. // To enable/disable IDB support and avoid XHR on .manifest
  8853. this.enableOfflineSupport = false;
  8854. this.scenes = new Array();
  8855. this.postProcesses = new Array();
  8856. // Observables
  8857. /**
  8858. * Observable event triggered each time the rendering canvas is resized
  8859. */
  8860. this.onResizeObservable = new BABYLON.Observable();
  8861. /**
  8862. * Observable event triggered each time the canvas loses focus
  8863. */
  8864. this.onCanvasBlurObservable = new BABYLON.Observable();
  8865. /**
  8866. * Observable event triggered each time the canvas gains focus
  8867. */
  8868. this.onCanvasFocusObservable = new BABYLON.Observable();
  8869. /**
  8870. * Observable event triggered each time the canvas receives pointerout event
  8871. */
  8872. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  8873. /**
  8874. * Observable event triggered before each texture is initialized
  8875. */
  8876. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8877. //WebVR
  8878. this._vrDisplay = undefined;
  8879. this._vrSupported = false;
  8880. this._vrExclusivePointerMode = false;
  8881. // Uniform buffers list
  8882. this.disableUniformBuffers = false;
  8883. this._uniformBuffers = new Array();
  8884. // Observables
  8885. /**
  8886. * Observable raised when the engine begins a new frame
  8887. */
  8888. this.onBeginFrameObservable = new BABYLON.Observable();
  8889. /**
  8890. * Observable raised when the engine ends the current frame
  8891. */
  8892. this.onEndFrameObservable = new BABYLON.Observable();
  8893. /**
  8894. * Observable raised when the engine is about to compile a shader
  8895. */
  8896. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8897. /**
  8898. * Observable raised when the engine has jsut compiled a shader
  8899. */
  8900. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8901. this._windowIsBackground = false;
  8902. this._webGLVersion = 1.0;
  8903. this._badOS = false;
  8904. this._badDesktopOS = false;
  8905. /**
  8906. * Gets or sets a value indicating if we want to disable texture binding optmization.
  8907. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  8908. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  8909. */
  8910. this.disableTextureBindingOptimization = false;
  8911. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8912. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8913. this.onVRRequestPresentStart = new BABYLON.Observable();
  8914. this._colorWrite = true;
  8915. this._drawCalls = new BABYLON.PerfCounter();
  8916. this._textureCollisions = new BABYLON.PerfCounter();
  8917. this._renderingQueueLaunched = false;
  8918. this._activeRenderLoops = new Array();
  8919. // Deterministic lockstepMaxSteps
  8920. this._deterministicLockstep = false;
  8921. this._lockstepMaxSteps = 4;
  8922. // Lost context
  8923. this.onContextLostObservable = new BABYLON.Observable();
  8924. this.onContextRestoredObservable = new BABYLON.Observable();
  8925. this._contextWasLost = false;
  8926. this._doNotHandleContextLost = false;
  8927. // FPS
  8928. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8929. this._fps = 60;
  8930. this._deltaTime = 0;
  8931. /**
  8932. * Turn this value on if you want to pause FPS computation when in background
  8933. */
  8934. this.disablePerformanceMonitorInBackground = false;
  8935. // States
  8936. this._depthCullingState = new BABYLON._DepthCullingState();
  8937. this._stencilState = new BABYLON._StencilState();
  8938. this._alphaState = new BABYLON._AlphaState();
  8939. this._alphaMode = Engine.ALPHA_DISABLE;
  8940. // Cache
  8941. this._internalTexturesCache = new Array();
  8942. this._boundTexturesCache = {};
  8943. this._boundTexturesStack = new Array();
  8944. this._compiledEffects = {};
  8945. this._vertexAttribArraysEnabled = [];
  8946. this._uintIndicesCurrentlySet = false;
  8947. this._currentBoundBuffer = new Array();
  8948. this._currentBufferPointers = new Array();
  8949. this._currentInstanceLocations = new Array();
  8950. this._currentInstanceBuffers = new Array();
  8951. this._vaoRecordInProgress = false;
  8952. this._mustWipeVertexAttributes = false;
  8953. this._nextFreeTextureSlots = new Array();
  8954. this._maxSimultaneousTextures = 0;
  8955. this._activeRequests = new Array();
  8956. // Hardware supported Compressed Textures
  8957. this._texturesSupported = new Array();
  8958. this._onVRFullScreenTriggered = function () {
  8959. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8960. //get the old size before we change
  8961. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8962. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8963. //get the width and height, change the render size
  8964. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8965. _this.setHardwareScalingLevel(1);
  8966. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8967. }
  8968. else {
  8969. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8970. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8971. }
  8972. };
  8973. this._boundUniforms = {};
  8974. var canvas = null;
  8975. Engine.Instances.push(this);
  8976. if (!canvasOrContext) {
  8977. return;
  8978. }
  8979. options = options || {};
  8980. if (canvasOrContext.getContext) {
  8981. canvas = canvasOrContext;
  8982. this._renderingCanvas = canvas;
  8983. if (antialias != null) {
  8984. options.antialias = antialias;
  8985. }
  8986. if (options.deterministicLockstep === undefined) {
  8987. options.deterministicLockstep = false;
  8988. }
  8989. if (options.lockstepMaxSteps === undefined) {
  8990. options.lockstepMaxSteps = 4;
  8991. }
  8992. if (options.preserveDrawingBuffer === undefined) {
  8993. options.preserveDrawingBuffer = false;
  8994. }
  8995. if (options.audioEngine === undefined) {
  8996. options.audioEngine = true;
  8997. }
  8998. if (options.stencil === undefined) {
  8999. options.stencil = true;
  9000. }
  9001. this._deterministicLockstep = options.deterministicLockstep;
  9002. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9003. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9004. // Exceptions
  9005. if (navigator && navigator.userAgent) {
  9006. var ua = navigator.userAgent;
  9007. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9008. var exception = _a[_i];
  9009. var key = exception.key;
  9010. var targets = exception.targets;
  9011. if (ua.indexOf(key) > -1) {
  9012. if (exception.capture && exception.captureConstraint) {
  9013. var capture = exception.capture;
  9014. var constraint = exception.captureConstraint;
  9015. var regex = new RegExp(capture);
  9016. var matches = regex.exec(ua);
  9017. if (matches && matches.length > 0) {
  9018. var capturedValue = parseInt(matches[matches.length - 1]);
  9019. if (capturedValue >= constraint) {
  9020. continue;
  9021. }
  9022. }
  9023. }
  9024. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9025. var target = targets_1[_b];
  9026. switch (target) {
  9027. case "uniformBuffer":
  9028. this.disableUniformBuffers = true;
  9029. break;
  9030. case "textureBindingOptimization":
  9031. this.disableTextureBindingOptimization = true;
  9032. break;
  9033. }
  9034. }
  9035. break;
  9036. }
  9037. }
  9038. }
  9039. // GL
  9040. if (!options.disableWebGL2Support) {
  9041. try {
  9042. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9043. if (this._gl) {
  9044. this._webGLVersion = 2.0;
  9045. }
  9046. }
  9047. catch (e) {
  9048. // Do nothing
  9049. }
  9050. }
  9051. if (!this._gl) {
  9052. if (!canvas) {
  9053. throw new Error("The provided canvas is null or undefined.");
  9054. }
  9055. try {
  9056. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9057. }
  9058. catch (e) {
  9059. throw new Error("WebGL not supported");
  9060. }
  9061. }
  9062. if (!this._gl) {
  9063. throw new Error("WebGL not supported");
  9064. }
  9065. this._onCanvasFocus = function () {
  9066. _this.onCanvasFocusObservable.notifyObservers(_this);
  9067. };
  9068. this._onCanvasBlur = function () {
  9069. _this.onCanvasBlurObservable.notifyObservers(_this);
  9070. };
  9071. canvas.addEventListener("focus", this._onCanvasFocus);
  9072. canvas.addEventListener("blur", this._onCanvasBlur);
  9073. this._onBlur = function () {
  9074. if (_this.disablePerformanceMonitorInBackground) {
  9075. _this._performanceMonitor.disable();
  9076. }
  9077. _this._windowIsBackground = true;
  9078. };
  9079. this._onFocus = function () {
  9080. if (_this.disablePerformanceMonitorInBackground) {
  9081. _this._performanceMonitor.enable();
  9082. }
  9083. _this._windowIsBackground = false;
  9084. };
  9085. this._onCanvasPointerOut = function () {
  9086. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9087. };
  9088. window.addEventListener("blur", this._onBlur);
  9089. window.addEventListener("focus", this._onFocus);
  9090. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9091. // Context lost
  9092. if (!this._doNotHandleContextLost) {
  9093. this._onContextLost = function (evt) {
  9094. evt.preventDefault();
  9095. _this._contextWasLost = true;
  9096. BABYLON.Tools.Warn("WebGL context lost.");
  9097. _this.onContextLostObservable.notifyObservers(_this);
  9098. };
  9099. this._onContextRestored = function (evt) {
  9100. // Adding a timeout to avoid race condition at browser level
  9101. setTimeout(function () {
  9102. // Rebuild gl context
  9103. _this._initGLContext();
  9104. // Rebuild effects
  9105. _this._rebuildEffects();
  9106. // Rebuild textures
  9107. _this._rebuildInternalTextures();
  9108. // Rebuild buffers
  9109. _this._rebuildBuffers();
  9110. // Cache
  9111. _this.wipeCaches(true);
  9112. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9113. _this.onContextRestoredObservable.notifyObservers(_this);
  9114. _this._contextWasLost = false;
  9115. }, 0);
  9116. };
  9117. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9118. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9119. }
  9120. }
  9121. else {
  9122. this._gl = canvasOrContext;
  9123. this._renderingCanvas = this._gl.canvas;
  9124. if (this._gl.renderbufferStorageMultisample) {
  9125. this._webGLVersion = 2.0;
  9126. }
  9127. options.stencil = this._gl.getContextAttributes().stencil;
  9128. }
  9129. // Viewport
  9130. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9131. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9132. this.resize();
  9133. this._isStencilEnable = options.stencil ? true : false;
  9134. this._initGLContext();
  9135. if (canvas) {
  9136. // Fullscreen
  9137. this._onFullscreenChange = function () {
  9138. if (document.fullscreen !== undefined) {
  9139. _this.isFullscreen = document.fullscreen;
  9140. }
  9141. else if (document.mozFullScreen !== undefined) {
  9142. _this.isFullscreen = document.mozFullScreen;
  9143. }
  9144. else if (document.webkitIsFullScreen !== undefined) {
  9145. _this.isFullscreen = document.webkitIsFullScreen;
  9146. }
  9147. else if (document.msIsFullScreen !== undefined) {
  9148. _this.isFullscreen = document.msIsFullScreen;
  9149. }
  9150. // Pointer lock
  9151. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9152. canvas.requestPointerLock = canvas.requestPointerLock ||
  9153. canvas.msRequestPointerLock ||
  9154. canvas.mozRequestPointerLock ||
  9155. canvas.webkitRequestPointerLock;
  9156. if (canvas.requestPointerLock) {
  9157. canvas.requestPointerLock();
  9158. }
  9159. }
  9160. };
  9161. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9162. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9163. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9164. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9165. // Pointer lock
  9166. this._onPointerLockChange = function () {
  9167. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9168. document.webkitPointerLockElement === canvas ||
  9169. document.msPointerLockElement === canvas ||
  9170. document.pointerLockElement === canvas);
  9171. };
  9172. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9173. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9174. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9175. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9176. this._onVRDisplayPointerRestricted = function () {
  9177. if (canvas) {
  9178. canvas.requestPointerLock();
  9179. }
  9180. };
  9181. this._onVRDisplayPointerUnrestricted = function () {
  9182. document.exitPointerLock();
  9183. };
  9184. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9185. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9186. }
  9187. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9188. Engine.audioEngine = new BABYLON.AudioEngine();
  9189. }
  9190. // Prepare buffer pointers
  9191. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9192. this._currentBufferPointers[i] = new BufferPointer();
  9193. }
  9194. // Load WebVR Devices
  9195. if (options.autoEnableWebVR) {
  9196. this.initWebVR();
  9197. }
  9198. // Detect if we are running on a faulty buggy OS.
  9199. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9200. // Detect if we are running on a faulty buggy desktop OS.
  9201. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9202. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9203. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9204. }
  9205. Object.defineProperty(Engine, "LastCreatedEngine", {
  9206. get: function () {
  9207. if (Engine.Instances.length === 0) {
  9208. return null;
  9209. }
  9210. return Engine.Instances[Engine.Instances.length - 1];
  9211. },
  9212. enumerable: true,
  9213. configurable: true
  9214. });
  9215. Object.defineProperty(Engine, "LastCreatedScene", {
  9216. get: function () {
  9217. var lastCreatedEngine = Engine.LastCreatedEngine;
  9218. if (!lastCreatedEngine) {
  9219. return null;
  9220. }
  9221. if (lastCreatedEngine.scenes.length === 0) {
  9222. return null;
  9223. }
  9224. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9225. },
  9226. enumerable: true,
  9227. configurable: true
  9228. });
  9229. /**
  9230. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9231. */
  9232. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9233. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9234. var engine = Engine.Instances[engineIndex];
  9235. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9236. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9237. }
  9238. }
  9239. };
  9240. Object.defineProperty(Engine, "NEVER", {
  9241. get: function () {
  9242. return Engine._NEVER;
  9243. },
  9244. enumerable: true,
  9245. configurable: true
  9246. });
  9247. Object.defineProperty(Engine, "ALWAYS", {
  9248. get: function () {
  9249. return Engine._ALWAYS;
  9250. },
  9251. enumerable: true,
  9252. configurable: true
  9253. });
  9254. Object.defineProperty(Engine, "LESS", {
  9255. get: function () {
  9256. return Engine._LESS;
  9257. },
  9258. enumerable: true,
  9259. configurable: true
  9260. });
  9261. Object.defineProperty(Engine, "EQUAL", {
  9262. get: function () {
  9263. return Engine._EQUAL;
  9264. },
  9265. enumerable: true,
  9266. configurable: true
  9267. });
  9268. Object.defineProperty(Engine, "LEQUAL", {
  9269. get: function () {
  9270. return Engine._LEQUAL;
  9271. },
  9272. enumerable: true,
  9273. configurable: true
  9274. });
  9275. Object.defineProperty(Engine, "GREATER", {
  9276. get: function () {
  9277. return Engine._GREATER;
  9278. },
  9279. enumerable: true,
  9280. configurable: true
  9281. });
  9282. Object.defineProperty(Engine, "GEQUAL", {
  9283. get: function () {
  9284. return Engine._GEQUAL;
  9285. },
  9286. enumerable: true,
  9287. configurable: true
  9288. });
  9289. Object.defineProperty(Engine, "NOTEQUAL", {
  9290. get: function () {
  9291. return Engine._NOTEQUAL;
  9292. },
  9293. enumerable: true,
  9294. configurable: true
  9295. });
  9296. Object.defineProperty(Engine, "KEEP", {
  9297. get: function () {
  9298. return Engine._KEEP;
  9299. },
  9300. enumerable: true,
  9301. configurable: true
  9302. });
  9303. Object.defineProperty(Engine, "REPLACE", {
  9304. get: function () {
  9305. return Engine._REPLACE;
  9306. },
  9307. enumerable: true,
  9308. configurable: true
  9309. });
  9310. Object.defineProperty(Engine, "INCR", {
  9311. get: function () {
  9312. return Engine._INCR;
  9313. },
  9314. enumerable: true,
  9315. configurable: true
  9316. });
  9317. Object.defineProperty(Engine, "DECR", {
  9318. get: function () {
  9319. return Engine._DECR;
  9320. },
  9321. enumerable: true,
  9322. configurable: true
  9323. });
  9324. Object.defineProperty(Engine, "INVERT", {
  9325. get: function () {
  9326. return Engine._INVERT;
  9327. },
  9328. enumerable: true,
  9329. configurable: true
  9330. });
  9331. Object.defineProperty(Engine, "INCR_WRAP", {
  9332. get: function () {
  9333. return Engine._INCR_WRAP;
  9334. },
  9335. enumerable: true,
  9336. configurable: true
  9337. });
  9338. Object.defineProperty(Engine, "DECR_WRAP", {
  9339. get: function () {
  9340. return Engine._DECR_WRAP;
  9341. },
  9342. enumerable: true,
  9343. configurable: true
  9344. });
  9345. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9346. get: function () {
  9347. return Engine._ALPHA_DISABLE;
  9348. },
  9349. enumerable: true,
  9350. configurable: true
  9351. });
  9352. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9353. get: function () {
  9354. return Engine._ALPHA_ONEONE;
  9355. },
  9356. enumerable: true,
  9357. configurable: true
  9358. });
  9359. Object.defineProperty(Engine, "ALPHA_ADD", {
  9360. get: function () {
  9361. return Engine._ALPHA_ADD;
  9362. },
  9363. enumerable: true,
  9364. configurable: true
  9365. });
  9366. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9367. get: function () {
  9368. return Engine._ALPHA_COMBINE;
  9369. },
  9370. enumerable: true,
  9371. configurable: true
  9372. });
  9373. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9374. get: function () {
  9375. return Engine._ALPHA_SUBTRACT;
  9376. },
  9377. enumerable: true,
  9378. configurable: true
  9379. });
  9380. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9381. get: function () {
  9382. return Engine._ALPHA_MULTIPLY;
  9383. },
  9384. enumerable: true,
  9385. configurable: true
  9386. });
  9387. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9388. get: function () {
  9389. return Engine._ALPHA_MAXIMIZED;
  9390. },
  9391. enumerable: true,
  9392. configurable: true
  9393. });
  9394. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9395. get: function () {
  9396. return Engine._ALPHA_PREMULTIPLIED;
  9397. },
  9398. enumerable: true,
  9399. configurable: true
  9400. });
  9401. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9402. get: function () {
  9403. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9404. },
  9405. enumerable: true,
  9406. configurable: true
  9407. });
  9408. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9409. get: function () {
  9410. return Engine._ALPHA_INTERPOLATE;
  9411. },
  9412. enumerable: true,
  9413. configurable: true
  9414. });
  9415. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9416. get: function () {
  9417. return Engine._ALPHA_SCREENMODE;
  9418. },
  9419. enumerable: true,
  9420. configurable: true
  9421. });
  9422. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9423. get: function () {
  9424. return Engine._DELAYLOADSTATE_NONE;
  9425. },
  9426. enumerable: true,
  9427. configurable: true
  9428. });
  9429. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9430. get: function () {
  9431. return Engine._DELAYLOADSTATE_LOADED;
  9432. },
  9433. enumerable: true,
  9434. configurable: true
  9435. });
  9436. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  9437. get: function () {
  9438. return Engine._DELAYLOADSTATE_LOADING;
  9439. },
  9440. enumerable: true,
  9441. configurable: true
  9442. });
  9443. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  9444. get: function () {
  9445. return Engine._DELAYLOADSTATE_NOTLOADED;
  9446. },
  9447. enumerable: true,
  9448. configurable: true
  9449. });
  9450. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  9451. get: function () {
  9452. return Engine._TEXTUREFORMAT_ALPHA;
  9453. },
  9454. enumerable: true,
  9455. configurable: true
  9456. });
  9457. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  9458. get: function () {
  9459. return Engine._TEXTUREFORMAT_LUMINANCE;
  9460. },
  9461. enumerable: true,
  9462. configurable: true
  9463. });
  9464. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  9465. get: function () {
  9466. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  9467. },
  9468. enumerable: true,
  9469. configurable: true
  9470. });
  9471. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  9472. get: function () {
  9473. return Engine._TEXTUREFORMAT_RGB;
  9474. },
  9475. enumerable: true,
  9476. configurable: true
  9477. });
  9478. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  9479. get: function () {
  9480. return Engine._TEXTUREFORMAT_RGBA;
  9481. },
  9482. enumerable: true,
  9483. configurable: true
  9484. });
  9485. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  9486. get: function () {
  9487. return Engine._TEXTURETYPE_UNSIGNED_INT;
  9488. },
  9489. enumerable: true,
  9490. configurable: true
  9491. });
  9492. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  9493. get: function () {
  9494. return Engine._TEXTURETYPE_FLOAT;
  9495. },
  9496. enumerable: true,
  9497. configurable: true
  9498. });
  9499. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  9500. get: function () {
  9501. return Engine._TEXTURETYPE_HALF_FLOAT;
  9502. },
  9503. enumerable: true,
  9504. configurable: true
  9505. });
  9506. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  9507. get: function () {
  9508. return Engine._SCALEMODE_FLOOR;
  9509. },
  9510. enumerable: true,
  9511. configurable: true
  9512. });
  9513. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  9514. get: function () {
  9515. return Engine._SCALEMODE_NEAREST;
  9516. },
  9517. enumerable: true,
  9518. configurable: true
  9519. });
  9520. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  9521. get: function () {
  9522. return Engine._SCALEMODE_CEILING;
  9523. },
  9524. enumerable: true,
  9525. configurable: true
  9526. });
  9527. Object.defineProperty(Engine, "Version", {
  9528. get: function () {
  9529. return "3.2.0-alpha4";
  9530. },
  9531. enumerable: true,
  9532. configurable: true
  9533. });
  9534. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  9535. get: function () {
  9536. return this._vrExclusivePointerMode;
  9537. },
  9538. enumerable: true,
  9539. configurable: true
  9540. });
  9541. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  9542. get: function () {
  9543. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  9544. },
  9545. enumerable: true,
  9546. configurable: true
  9547. });
  9548. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  9549. get: function () {
  9550. return this._webGLVersion < 2 || this.forcePOTTextures;
  9551. },
  9552. enumerable: true,
  9553. configurable: true
  9554. });
  9555. Object.defineProperty(Engine.prototype, "badOS", {
  9556. get: function () {
  9557. return this._badOS;
  9558. },
  9559. enumerable: true,
  9560. configurable: true
  9561. });
  9562. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  9563. get: function () {
  9564. return this._badDesktopOS;
  9565. },
  9566. enumerable: true,
  9567. configurable: true
  9568. });
  9569. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  9570. get: function () {
  9571. return this._performanceMonitor;
  9572. },
  9573. enumerable: true,
  9574. configurable: true
  9575. });
  9576. Object.defineProperty(Engine.prototype, "texturesSupported", {
  9577. get: function () {
  9578. return this._texturesSupported;
  9579. },
  9580. enumerable: true,
  9581. configurable: true
  9582. });
  9583. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  9584. get: function () {
  9585. return this._textureFormatInUse;
  9586. },
  9587. enumerable: true,
  9588. configurable: true
  9589. });
  9590. Object.defineProperty(Engine.prototype, "currentViewport", {
  9591. get: function () {
  9592. return this._cachedViewport;
  9593. },
  9594. enumerable: true,
  9595. configurable: true
  9596. });
  9597. Object.defineProperty(Engine.prototype, "emptyTexture", {
  9598. // Empty texture
  9599. get: function () {
  9600. if (!this._emptyTexture) {
  9601. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9602. }
  9603. return this._emptyTexture;
  9604. },
  9605. enumerable: true,
  9606. configurable: true
  9607. });
  9608. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  9609. get: function () {
  9610. if (!this._emptyTexture3D) {
  9611. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9612. }
  9613. return this._emptyTexture3D;
  9614. },
  9615. enumerable: true,
  9616. configurable: true
  9617. });
  9618. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  9619. get: function () {
  9620. if (!this._emptyCubeTexture) {
  9621. var faceData = new Uint8Array(4);
  9622. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  9623. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9624. }
  9625. return this._emptyCubeTexture;
  9626. },
  9627. enumerable: true,
  9628. configurable: true
  9629. });
  9630. Engine.prototype._rebuildInternalTextures = function () {
  9631. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  9632. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  9633. var internalTexture = currentState_1[_i];
  9634. internalTexture._rebuild();
  9635. }
  9636. };
  9637. Engine.prototype._rebuildEffects = function () {
  9638. for (var key in this._compiledEffects) {
  9639. var effect = this._compiledEffects[key];
  9640. effect._prepareEffect();
  9641. }
  9642. BABYLON.Effect.ResetCache();
  9643. };
  9644. Engine.prototype._rebuildBuffers = function () {
  9645. // Index / Vertex
  9646. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  9647. var scene = _a[_i];
  9648. scene.resetCachedMaterial();
  9649. scene._rebuildGeometries();
  9650. scene._rebuildTextures();
  9651. }
  9652. // Uniforms
  9653. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  9654. var uniformBuffer = _c[_b];
  9655. uniformBuffer._rebuild();
  9656. }
  9657. };
  9658. Engine.prototype._initGLContext = function () {
  9659. // Caps
  9660. this._caps = new EngineCapabilities();
  9661. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  9662. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  9663. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9664. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  9665. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9666. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  9667. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  9668. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  9669. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9670. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  9671. // Infos
  9672. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  9673. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  9674. if (rendererInfo != null) {
  9675. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  9676. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  9677. }
  9678. if (!this._glVendor) {
  9679. this._glVendor = "Unknown vendor";
  9680. }
  9681. if (!this._glRenderer) {
  9682. this._glRenderer = "Unknown renderer";
  9683. }
  9684. // Constants
  9685. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9686. if (this._gl.RGBA16F !== 0x881A) {
  9687. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9688. }
  9689. if (this._gl.RGBA32F !== 0x8814) {
  9690. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9691. }
  9692. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  9693. this._gl.DEPTH24_STENCIL8 = 35056;
  9694. }
  9695. // Extensions
  9696. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  9697. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  9698. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9699. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9700. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  9701. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  9702. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  9703. 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');
  9704. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  9705. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  9706. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  9707. this._caps.highPrecisionShaderSupported = true;
  9708. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  9709. if (this._caps.timerQuery) {
  9710. if (this._webGLVersion === 1) {
  9711. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  9712. }
  9713. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  9714. }
  9715. // Checks if some of the format renders first to allow the use of webgl inspector.
  9716. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  9717. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  9718. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  9719. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  9720. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  9721. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  9722. if (this._webGLVersion > 1) {
  9723. this._gl.HALF_FLOAT_OES = 0x140B;
  9724. }
  9725. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  9726. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  9727. // Draw buffers
  9728. if (this._webGLVersion > 1) {
  9729. this._caps.drawBuffersExtension = true;
  9730. }
  9731. else {
  9732. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  9733. if (drawBuffersExtension !== null) {
  9734. this._caps.drawBuffersExtension = true;
  9735. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  9736. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  9737. for (var i = 0; i < 16; i++) {
  9738. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  9739. }
  9740. }
  9741. else {
  9742. this._caps.drawBuffersExtension = false;
  9743. }
  9744. }
  9745. // Depth Texture
  9746. if (this._webGLVersion > 1) {
  9747. this._caps.depthTextureExtension = true;
  9748. }
  9749. else {
  9750. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  9751. if (depthTextureExtension != null) {
  9752. this._caps.depthTextureExtension = true;
  9753. }
  9754. }
  9755. // Vertex array object
  9756. if (this._webGLVersion > 1) {
  9757. this._caps.vertexArrayObject = true;
  9758. }
  9759. else {
  9760. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  9761. if (vertexArrayObjectExtension != null) {
  9762. this._caps.vertexArrayObject = true;
  9763. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  9764. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  9765. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  9766. }
  9767. else {
  9768. this._caps.vertexArrayObject = false;
  9769. }
  9770. }
  9771. // Instances count
  9772. if (this._webGLVersion > 1) {
  9773. this._caps.instancedArrays = true;
  9774. }
  9775. else {
  9776. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  9777. if (instanceExtension != null) {
  9778. this._caps.instancedArrays = true;
  9779. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  9780. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  9781. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  9782. }
  9783. else {
  9784. this._caps.instancedArrays = false;
  9785. }
  9786. }
  9787. // Intelligently add supported compressed formats in order to check for.
  9788. // Check for ASTC support first as it is most powerful and to be very cross platform.
  9789. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  9790. // Likely no hardware which supports both PVR & DXT, so order matters little.
  9791. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  9792. if (this._caps.astc)
  9793. this.texturesSupported.push('-astc.ktx');
  9794. if (this._caps.s3tc)
  9795. this.texturesSupported.push('-dxt.ktx');
  9796. if (this._caps.pvrtc)
  9797. this.texturesSupported.push('-pvrtc.ktx');
  9798. if (this._caps.etc2)
  9799. this.texturesSupported.push('-etc2.ktx');
  9800. if (this._caps.etc1)
  9801. this.texturesSupported.push('-etc1.ktx');
  9802. if (this._gl.getShaderPrecisionFormat) {
  9803. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  9804. if (highp) {
  9805. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  9806. }
  9807. }
  9808. // Depth buffer
  9809. this.setDepthBuffer(true);
  9810. this.setDepthFunctionToLessOrEqual();
  9811. this.setDepthWrite(true);
  9812. // Texture maps
  9813. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  9814. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  9815. this._nextFreeTextureSlots.push(slot);
  9816. }
  9817. };
  9818. Object.defineProperty(Engine.prototype, "webGLVersion", {
  9819. get: function () {
  9820. return this._webGLVersion;
  9821. },
  9822. enumerable: true,
  9823. configurable: true
  9824. });
  9825. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  9826. /**
  9827. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  9828. */
  9829. get: function () {
  9830. return this._isStencilEnable;
  9831. },
  9832. enumerable: true,
  9833. configurable: true
  9834. });
  9835. Engine.prototype._prepareWorkingCanvas = function () {
  9836. if (this._workingCanvas) {
  9837. return;
  9838. }
  9839. this._workingCanvas = document.createElement("canvas");
  9840. var context = this._workingCanvas.getContext("2d");
  9841. if (context) {
  9842. this._workingContext = context;
  9843. }
  9844. };
  9845. Engine.prototype.resetTextureCache = function () {
  9846. for (var key in this._boundTexturesCache) {
  9847. var boundTexture = this._boundTexturesCache[key];
  9848. if (boundTexture) {
  9849. this._removeDesignatedSlot(boundTexture);
  9850. }
  9851. this._boundTexturesCache[key] = null;
  9852. }
  9853. this._nextFreeTextureSlots = [];
  9854. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  9855. this._nextFreeTextureSlots.push(slot);
  9856. }
  9857. this._activeChannel = -1;
  9858. };
  9859. Engine.prototype.isDeterministicLockStep = function () {
  9860. return this._deterministicLockstep;
  9861. };
  9862. Engine.prototype.getLockstepMaxSteps = function () {
  9863. return this._lockstepMaxSteps;
  9864. };
  9865. Engine.prototype.getGlInfo = function () {
  9866. return {
  9867. vendor: this._glVendor,
  9868. renderer: this._glRenderer,
  9869. version: this._glVersion
  9870. };
  9871. };
  9872. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  9873. if (useScreen === void 0) { useScreen = false; }
  9874. var viewport = camera.viewport;
  9875. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  9876. };
  9877. Engine.prototype.getRenderWidth = function (useScreen) {
  9878. if (useScreen === void 0) { useScreen = false; }
  9879. if (!useScreen && this._currentRenderTarget) {
  9880. return this._currentRenderTarget.width;
  9881. }
  9882. return this._gl.drawingBufferWidth;
  9883. };
  9884. Engine.prototype.getRenderHeight = function (useScreen) {
  9885. if (useScreen === void 0) { useScreen = false; }
  9886. if (!useScreen && this._currentRenderTarget) {
  9887. return this._currentRenderTarget.height;
  9888. }
  9889. return this._gl.drawingBufferHeight;
  9890. };
  9891. Engine.prototype.getRenderingCanvas = function () {
  9892. return this._renderingCanvas;
  9893. };
  9894. Engine.prototype.getRenderingCanvasClientRect = function () {
  9895. if (!this._renderingCanvas) {
  9896. return null;
  9897. }
  9898. return this._renderingCanvas.getBoundingClientRect();
  9899. };
  9900. Engine.prototype.setHardwareScalingLevel = function (level) {
  9901. this._hardwareScalingLevel = level;
  9902. this.resize();
  9903. };
  9904. Engine.prototype.getHardwareScalingLevel = function () {
  9905. return this._hardwareScalingLevel;
  9906. };
  9907. Engine.prototype.getLoadedTexturesCache = function () {
  9908. return this._internalTexturesCache;
  9909. };
  9910. Engine.prototype.getCaps = function () {
  9911. return this._caps;
  9912. };
  9913. Object.defineProperty(Engine.prototype, "drawCalls", {
  9914. /** The number of draw calls submitted last frame */
  9915. get: function () {
  9916. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  9917. return 0;
  9918. },
  9919. enumerable: true,
  9920. configurable: true
  9921. });
  9922. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  9923. get: function () {
  9924. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  9925. return null;
  9926. },
  9927. enumerable: true,
  9928. configurable: true
  9929. });
  9930. Engine.prototype.getDepthFunction = function () {
  9931. return this._depthCullingState.depthFunc;
  9932. };
  9933. Engine.prototype.setDepthFunction = function (depthFunc) {
  9934. this._depthCullingState.depthFunc = depthFunc;
  9935. };
  9936. Engine.prototype.setDepthFunctionToGreater = function () {
  9937. this._depthCullingState.depthFunc = this._gl.GREATER;
  9938. };
  9939. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  9940. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  9941. };
  9942. Engine.prototype.setDepthFunctionToLess = function () {
  9943. this._depthCullingState.depthFunc = this._gl.LESS;
  9944. };
  9945. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  9946. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  9947. };
  9948. Engine.prototype.getStencilBuffer = function () {
  9949. return this._stencilState.stencilTest;
  9950. };
  9951. Engine.prototype.setStencilBuffer = function (enable) {
  9952. this._stencilState.stencilTest = enable;
  9953. };
  9954. Engine.prototype.getStencilMask = function () {
  9955. return this._stencilState.stencilMask;
  9956. };
  9957. Engine.prototype.setStencilMask = function (mask) {
  9958. this._stencilState.stencilMask = mask;
  9959. };
  9960. Engine.prototype.getStencilFunction = function () {
  9961. return this._stencilState.stencilFunc;
  9962. };
  9963. Engine.prototype.getStencilFunctionReference = function () {
  9964. return this._stencilState.stencilFuncRef;
  9965. };
  9966. Engine.prototype.getStencilFunctionMask = function () {
  9967. return this._stencilState.stencilFuncMask;
  9968. };
  9969. Engine.prototype.setStencilFunction = function (stencilFunc) {
  9970. this._stencilState.stencilFunc = stencilFunc;
  9971. };
  9972. Engine.prototype.setStencilFunctionReference = function (reference) {
  9973. this._stencilState.stencilFuncRef = reference;
  9974. };
  9975. Engine.prototype.setStencilFunctionMask = function (mask) {
  9976. this._stencilState.stencilFuncMask = mask;
  9977. };
  9978. Engine.prototype.getStencilOperationFail = function () {
  9979. return this._stencilState.stencilOpStencilFail;
  9980. };
  9981. Engine.prototype.getStencilOperationDepthFail = function () {
  9982. return this._stencilState.stencilOpDepthFail;
  9983. };
  9984. Engine.prototype.getStencilOperationPass = function () {
  9985. return this._stencilState.stencilOpStencilDepthPass;
  9986. };
  9987. Engine.prototype.setStencilOperationFail = function (operation) {
  9988. this._stencilState.stencilOpStencilFail = operation;
  9989. };
  9990. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  9991. this._stencilState.stencilOpDepthFail = operation;
  9992. };
  9993. Engine.prototype.setStencilOperationPass = function (operation) {
  9994. this._stencilState.stencilOpStencilDepthPass = operation;
  9995. };
  9996. Engine.prototype.setDitheringState = function (value) {
  9997. if (value) {
  9998. this._gl.enable(this._gl.DITHER);
  9999. }
  10000. else {
  10001. this._gl.disable(this._gl.DITHER);
  10002. }
  10003. };
  10004. Engine.prototype.setRasterizerState = function (value) {
  10005. if (value) {
  10006. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10007. }
  10008. else {
  10009. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10010. }
  10011. };
  10012. /**
  10013. * stop executing a render loop function and remove it from the execution array
  10014. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10015. */
  10016. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10017. if (!renderFunction) {
  10018. this._activeRenderLoops = [];
  10019. return;
  10020. }
  10021. var index = this._activeRenderLoops.indexOf(renderFunction);
  10022. if (index >= 0) {
  10023. this._activeRenderLoops.splice(index, 1);
  10024. }
  10025. };
  10026. Engine.prototype._renderLoop = function () {
  10027. if (!this._contextWasLost) {
  10028. var shouldRender = true;
  10029. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10030. shouldRender = false;
  10031. }
  10032. if (shouldRender) {
  10033. // Start new frame
  10034. this.beginFrame();
  10035. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10036. var renderFunction = this._activeRenderLoops[index];
  10037. renderFunction();
  10038. }
  10039. // Present
  10040. this.endFrame();
  10041. }
  10042. }
  10043. if (this._activeRenderLoops.length > 0) {
  10044. // Register new frame
  10045. var requester = null;
  10046. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10047. requester = this._vrDisplay;
  10048. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10049. }
  10050. else {
  10051. this._renderingQueueLaunched = false;
  10052. }
  10053. };
  10054. /**
  10055. * Register and execute a render loop. The engine can have more than one render function.
  10056. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10057. * @example
  10058. * engine.runRenderLoop(function () {
  10059. * scene.render()
  10060. * })
  10061. */
  10062. Engine.prototype.runRenderLoop = function (renderFunction) {
  10063. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10064. return;
  10065. }
  10066. this._activeRenderLoops.push(renderFunction);
  10067. if (!this._renderingQueueLaunched) {
  10068. this._renderingQueueLaunched = true;
  10069. this._bindedRenderFunction = this._renderLoop.bind(this);
  10070. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10071. }
  10072. };
  10073. /**
  10074. * Toggle full screen mode.
  10075. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10076. * @param {any} options - an options object to be sent to the requestFullscreen function
  10077. */
  10078. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10079. if (this.isFullscreen) {
  10080. BABYLON.Tools.ExitFullscreen();
  10081. }
  10082. else {
  10083. this._pointerLockRequested = requestPointerLock;
  10084. if (this._renderingCanvas) {
  10085. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10086. }
  10087. }
  10088. };
  10089. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10090. if (stencil === void 0) { stencil = false; }
  10091. this.applyStates();
  10092. var mode = 0;
  10093. if (backBuffer && color) {
  10094. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10095. mode |= this._gl.COLOR_BUFFER_BIT;
  10096. }
  10097. if (depth) {
  10098. this._gl.clearDepth(1.0);
  10099. mode |= this._gl.DEPTH_BUFFER_BIT;
  10100. }
  10101. if (stencil) {
  10102. this._gl.clearStencil(0);
  10103. mode |= this._gl.STENCIL_BUFFER_BIT;
  10104. }
  10105. this._gl.clear(mode);
  10106. };
  10107. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10108. var gl = this._gl;
  10109. // Save state
  10110. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10111. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10112. // Change state
  10113. gl.enable(gl.SCISSOR_TEST);
  10114. gl.scissor(x, y, width, height);
  10115. // Clear
  10116. this.clear(clearColor, true, true, true);
  10117. // Restore state
  10118. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10119. if (curScissor === true) {
  10120. gl.enable(gl.SCISSOR_TEST);
  10121. }
  10122. else {
  10123. gl.disable(gl.SCISSOR_TEST);
  10124. }
  10125. };
  10126. /**
  10127. * Set the WebGL's viewport
  10128. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10129. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10130. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10131. */
  10132. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10133. var width = requiredWidth || this.getRenderWidth();
  10134. var height = requiredHeight || this.getRenderHeight();
  10135. var x = viewport.x || 0;
  10136. var y = viewport.y || 0;
  10137. this._cachedViewport = viewport;
  10138. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10139. };
  10140. /**
  10141. * Directly set the WebGL Viewport
  10142. * The x, y, width & height are directly passed to the WebGL call
  10143. * @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.
  10144. */
  10145. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10146. var currentViewport = this._cachedViewport;
  10147. this._cachedViewport = null;
  10148. this._gl.viewport(x, y, width, height);
  10149. return currentViewport;
  10150. };
  10151. Engine.prototype.beginFrame = function () {
  10152. this.onBeginFrameObservable.notifyObservers(this);
  10153. this._measureFps();
  10154. };
  10155. Engine.prototype.endFrame = function () {
  10156. //force a flush in case we are using a bad OS.
  10157. if (this._badOS) {
  10158. this.flushFramebuffer();
  10159. }
  10160. //submit frame to the vr device, if enabled
  10161. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10162. // TODO: We should only submit the frame if we read frameData successfully.
  10163. this._vrDisplay.submitFrame();
  10164. }
  10165. this.onEndFrameObservable.notifyObservers(this);
  10166. };
  10167. /**
  10168. * resize the view according to the canvas' size.
  10169. * @example
  10170. * window.addEventListener("resize", function () {
  10171. * engine.resize();
  10172. * });
  10173. */
  10174. Engine.prototype.resize = function () {
  10175. // We're not resizing the size of the canvas while in VR mode & presenting
  10176. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10177. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10178. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10179. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10180. }
  10181. };
  10182. /**
  10183. * force a specific size of the canvas
  10184. * @param {number} width - the new canvas' width
  10185. * @param {number} height - the new canvas' height
  10186. */
  10187. Engine.prototype.setSize = function (width, height) {
  10188. if (!this._renderingCanvas) {
  10189. return;
  10190. }
  10191. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10192. return;
  10193. }
  10194. this._renderingCanvas.width = width;
  10195. this._renderingCanvas.height = height;
  10196. for (var index = 0; index < this.scenes.length; index++) {
  10197. var scene = this.scenes[index];
  10198. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10199. var cam = scene.cameras[camIndex];
  10200. cam._currentRenderId = 0;
  10201. }
  10202. }
  10203. if (this.onResizeObservable.hasObservers) {
  10204. this.onResizeObservable.notifyObservers(this);
  10205. }
  10206. };
  10207. // WebVR functions
  10208. Engine.prototype.isVRDevicePresent = function () {
  10209. return !!this._vrDisplay;
  10210. };
  10211. Engine.prototype.getVRDevice = function () {
  10212. return this._vrDisplay;
  10213. };
  10214. Engine.prototype.initWebVR = function () {
  10215. var _this = this;
  10216. var notifyObservers = function () {
  10217. var eventArgs = {
  10218. vrDisplay: _this._vrDisplay,
  10219. vrSupported: _this._vrSupported
  10220. };
  10221. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10222. };
  10223. if (!this._onVrDisplayConnect) {
  10224. this._onVrDisplayConnect = function (event) {
  10225. _this._vrDisplay = event.display;
  10226. notifyObservers();
  10227. };
  10228. this._onVrDisplayDisconnect = function () {
  10229. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10230. _this._vrDisplay = undefined;
  10231. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10232. notifyObservers();
  10233. };
  10234. this._onVrDisplayPresentChange = function () {
  10235. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10236. };
  10237. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10238. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10239. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10240. }
  10241. this._getVRDisplays(notifyObservers);
  10242. return this.onVRDisplayChangedObservable;
  10243. };
  10244. Engine.prototype.enableVR = function () {
  10245. var _this = this;
  10246. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10247. var onResolved = function () {
  10248. _this.onVRRequestPresentComplete.notifyObservers(true);
  10249. _this._onVRFullScreenTriggered();
  10250. };
  10251. var onRejected = function () {
  10252. _this.onVRRequestPresentComplete.notifyObservers(false);
  10253. };
  10254. this.onVRRequestPresentStart.notifyObservers(this);
  10255. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10256. }
  10257. };
  10258. Engine.prototype.disableVR = function () {
  10259. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10260. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10261. }
  10262. };
  10263. Engine.prototype._getVRDisplays = function (callback) {
  10264. var _this = this;
  10265. var getWebVRDevices = function (devices) {
  10266. _this._vrSupported = true;
  10267. // note that devices may actually be an empty array. This is fine;
  10268. // we expect this._vrDisplay to be undefined in this case.
  10269. return _this._vrDisplay = devices[0];
  10270. };
  10271. if (navigator.getVRDisplays) {
  10272. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10273. // TODO: System CANNOT support WebVR, despite API presence.
  10274. _this._vrSupported = false;
  10275. callback();
  10276. });
  10277. }
  10278. else {
  10279. // TODO: Browser does not support WebVR
  10280. this._vrDisplay = undefined;
  10281. this._vrSupported = false;
  10282. callback();
  10283. }
  10284. };
  10285. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10286. if (this._currentRenderTarget) {
  10287. this.unBindFramebuffer(this._currentRenderTarget);
  10288. }
  10289. this._currentRenderTarget = texture;
  10290. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10291. var gl = this._gl;
  10292. if (texture.isCube) {
  10293. if (faceIndex === undefined) {
  10294. faceIndex = 0;
  10295. }
  10296. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10297. }
  10298. if (this._cachedViewport && !forceFullscreenViewport) {
  10299. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10300. }
  10301. else {
  10302. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10303. }
  10304. this.wipeCaches();
  10305. };
  10306. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10307. if (this._currentFramebuffer !== framebuffer) {
  10308. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10309. this._currentFramebuffer = framebuffer;
  10310. }
  10311. };
  10312. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10313. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10314. this._currentRenderTarget = null;
  10315. // If MSAA, we need to bitblt back to main texture
  10316. var gl = this._gl;
  10317. if (texture._MSAAFramebuffer) {
  10318. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10319. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10320. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10321. }
  10322. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10323. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10324. gl.generateMipmap(gl.TEXTURE_2D);
  10325. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10326. }
  10327. if (onBeforeUnbind) {
  10328. if (texture._MSAAFramebuffer) {
  10329. // Bind the correct framebuffer
  10330. this.bindUnboundFramebuffer(texture._framebuffer);
  10331. }
  10332. onBeforeUnbind();
  10333. }
  10334. this.bindUnboundFramebuffer(null);
  10335. };
  10336. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10337. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10338. this._currentRenderTarget = null;
  10339. // If MSAA, we need to bitblt back to main texture
  10340. var gl = this._gl;
  10341. if (textures[0]._MSAAFramebuffer) {
  10342. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10343. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10344. var attachments = textures[0]._attachments;
  10345. if (!attachments) {
  10346. attachments = new Array(textures.length);
  10347. textures[0]._attachments = attachments;
  10348. }
  10349. for (var i = 0; i < textures.length; i++) {
  10350. var texture = textures[i];
  10351. for (var j = 0; j < attachments.length; j++) {
  10352. attachments[j] = gl.NONE;
  10353. }
  10354. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10355. gl.readBuffer(attachments[i]);
  10356. gl.drawBuffers(attachments);
  10357. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10358. }
  10359. for (var i = 0; i < attachments.length; i++) {
  10360. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10361. }
  10362. gl.drawBuffers(attachments);
  10363. }
  10364. for (var i = 0; i < textures.length; i++) {
  10365. var texture = textures[i];
  10366. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10367. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10368. gl.generateMipmap(gl.TEXTURE_2D);
  10369. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10370. }
  10371. }
  10372. if (onBeforeUnbind) {
  10373. if (textures[0]._MSAAFramebuffer) {
  10374. // Bind the correct framebuffer
  10375. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10376. }
  10377. onBeforeUnbind();
  10378. }
  10379. this.bindUnboundFramebuffer(null);
  10380. };
  10381. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10382. if (texture.generateMipMaps) {
  10383. var gl = this._gl;
  10384. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10385. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10386. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10387. }
  10388. };
  10389. Engine.prototype.flushFramebuffer = function () {
  10390. this._gl.flush();
  10391. };
  10392. Engine.prototype.restoreDefaultFramebuffer = function () {
  10393. if (this._currentRenderTarget) {
  10394. this.unBindFramebuffer(this._currentRenderTarget);
  10395. }
  10396. else {
  10397. this.bindUnboundFramebuffer(null);
  10398. }
  10399. if (this._cachedViewport) {
  10400. this.setViewport(this._cachedViewport);
  10401. }
  10402. this.wipeCaches();
  10403. };
  10404. // UBOs
  10405. Engine.prototype.createUniformBuffer = function (elements) {
  10406. var ubo = this._gl.createBuffer();
  10407. if (!ubo) {
  10408. throw new Error("Unable to create uniform buffer");
  10409. }
  10410. this.bindUniformBuffer(ubo);
  10411. if (elements instanceof Float32Array) {
  10412. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10413. }
  10414. else {
  10415. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10416. }
  10417. this.bindUniformBuffer(null);
  10418. ubo.references = 1;
  10419. return ubo;
  10420. };
  10421. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10422. var ubo = this._gl.createBuffer();
  10423. if (!ubo) {
  10424. throw new Error("Unable to create dynamic uniform buffer");
  10425. }
  10426. this.bindUniformBuffer(ubo);
  10427. if (elements instanceof Float32Array) {
  10428. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10429. }
  10430. else {
  10431. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10432. }
  10433. this.bindUniformBuffer(null);
  10434. ubo.references = 1;
  10435. return ubo;
  10436. };
  10437. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  10438. this.bindUniformBuffer(uniformBuffer);
  10439. if (offset === undefined) {
  10440. offset = 0;
  10441. }
  10442. if (count === undefined) {
  10443. if (elements instanceof Float32Array) {
  10444. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  10445. }
  10446. else {
  10447. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  10448. }
  10449. }
  10450. else {
  10451. if (elements instanceof Float32Array) {
  10452. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  10453. }
  10454. else {
  10455. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  10456. }
  10457. }
  10458. this.bindUniformBuffer(null);
  10459. };
  10460. // VBOs
  10461. Engine.prototype._resetVertexBufferBinding = function () {
  10462. this.bindArrayBuffer(null);
  10463. this._cachedVertexBuffers = null;
  10464. };
  10465. Engine.prototype.createVertexBuffer = function (vertices) {
  10466. var vbo = this._gl.createBuffer();
  10467. if (!vbo) {
  10468. throw new Error("Unable to create vertex buffer");
  10469. }
  10470. this.bindArrayBuffer(vbo);
  10471. if (vertices instanceof Float32Array) {
  10472. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  10473. }
  10474. else {
  10475. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  10476. }
  10477. this._resetVertexBufferBinding();
  10478. vbo.references = 1;
  10479. return vbo;
  10480. };
  10481. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  10482. var vbo = this._gl.createBuffer();
  10483. if (!vbo) {
  10484. throw new Error("Unable to create dynamic vertex buffer");
  10485. }
  10486. this.bindArrayBuffer(vbo);
  10487. if (vertices instanceof Float32Array) {
  10488. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  10489. }
  10490. else {
  10491. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  10492. }
  10493. this._resetVertexBufferBinding();
  10494. vbo.references = 1;
  10495. return vbo;
  10496. };
  10497. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  10498. if (offset === void 0) { offset = 0; }
  10499. // Force cache update
  10500. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  10501. this.bindIndexBuffer(indexBuffer);
  10502. var arrayBuffer;
  10503. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  10504. arrayBuffer = indices;
  10505. }
  10506. else {
  10507. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10508. }
  10509. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  10510. this._resetIndexBufferBinding();
  10511. };
  10512. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  10513. this.bindArrayBuffer(vertexBuffer);
  10514. if (offset === undefined) {
  10515. offset = 0;
  10516. }
  10517. if (count === undefined) {
  10518. if (vertices instanceof Float32Array) {
  10519. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  10520. }
  10521. else {
  10522. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  10523. }
  10524. }
  10525. else {
  10526. if (vertices instanceof Float32Array) {
  10527. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  10528. }
  10529. else {
  10530. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  10531. }
  10532. }
  10533. this._resetVertexBufferBinding();
  10534. };
  10535. Engine.prototype._resetIndexBufferBinding = function () {
  10536. this.bindIndexBuffer(null);
  10537. this._cachedIndexBuffer = null;
  10538. };
  10539. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  10540. var vbo = this._gl.createBuffer();
  10541. if (!vbo) {
  10542. throw new Error("Unable to create index buffer");
  10543. }
  10544. this.bindIndexBuffer(vbo);
  10545. // Check for 32 bits indices
  10546. var arrayBuffer;
  10547. var need32Bits = false;
  10548. if (indices instanceof Uint16Array) {
  10549. arrayBuffer = indices;
  10550. }
  10551. else {
  10552. //check 32 bit support
  10553. if (this._caps.uintIndices) {
  10554. if (indices instanceof Uint32Array) {
  10555. arrayBuffer = indices;
  10556. need32Bits = true;
  10557. }
  10558. else {
  10559. //number[] or Int32Array, check if 32 bit is necessary
  10560. for (var index = 0; index < indices.length; index++) {
  10561. if (indices[index] > 65535) {
  10562. need32Bits = true;
  10563. break;
  10564. }
  10565. }
  10566. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10567. }
  10568. }
  10569. else {
  10570. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  10571. arrayBuffer = new Uint16Array(indices);
  10572. }
  10573. }
  10574. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  10575. this._resetIndexBufferBinding();
  10576. vbo.references = 1;
  10577. vbo.is32Bits = need32Bits;
  10578. return vbo;
  10579. };
  10580. Engine.prototype.bindArrayBuffer = function (buffer) {
  10581. if (!this._vaoRecordInProgress) {
  10582. this._unbindVertexArrayObject();
  10583. }
  10584. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  10585. };
  10586. Engine.prototype.bindUniformBuffer = function (buffer) {
  10587. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  10588. };
  10589. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  10590. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  10591. };
  10592. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  10593. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  10594. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  10595. };
  10596. ;
  10597. Engine.prototype.bindIndexBuffer = function (buffer) {
  10598. if (!this._vaoRecordInProgress) {
  10599. this._unbindVertexArrayObject();
  10600. }
  10601. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  10602. };
  10603. Engine.prototype.bindBuffer = function (buffer, target) {
  10604. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  10605. this._gl.bindBuffer(target, buffer);
  10606. this._currentBoundBuffer[target] = buffer;
  10607. }
  10608. };
  10609. Engine.prototype.updateArrayBuffer = function (data) {
  10610. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10611. };
  10612. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  10613. var pointer = this._currentBufferPointers[indx];
  10614. var changed = false;
  10615. if (!pointer.active) {
  10616. changed = true;
  10617. pointer.active = true;
  10618. pointer.index = indx;
  10619. pointer.size = size;
  10620. pointer.type = type;
  10621. pointer.normalized = normalized;
  10622. pointer.stride = stride;
  10623. pointer.offset = offset;
  10624. pointer.buffer = buffer;
  10625. }
  10626. else {
  10627. if (pointer.buffer !== buffer) {
  10628. pointer.buffer = buffer;
  10629. changed = true;
  10630. }
  10631. if (pointer.size !== size) {
  10632. pointer.size = size;
  10633. changed = true;
  10634. }
  10635. if (pointer.type !== type) {
  10636. pointer.type = type;
  10637. changed = true;
  10638. }
  10639. if (pointer.normalized !== normalized) {
  10640. pointer.normalized = normalized;
  10641. changed = true;
  10642. }
  10643. if (pointer.stride !== stride) {
  10644. pointer.stride = stride;
  10645. changed = true;
  10646. }
  10647. if (pointer.offset !== offset) {
  10648. pointer.offset = offset;
  10649. changed = true;
  10650. }
  10651. }
  10652. if (changed || this._vaoRecordInProgress) {
  10653. this.bindArrayBuffer(buffer);
  10654. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  10655. }
  10656. };
  10657. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  10658. if (indexBuffer == null) {
  10659. return;
  10660. }
  10661. if (this._cachedIndexBuffer !== indexBuffer) {
  10662. this._cachedIndexBuffer = indexBuffer;
  10663. this.bindIndexBuffer(indexBuffer);
  10664. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  10665. }
  10666. };
  10667. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  10668. var attributes = effect.getAttributesNames();
  10669. if (!this._vaoRecordInProgress) {
  10670. this._unbindVertexArrayObject();
  10671. }
  10672. this.unbindAllAttributes();
  10673. for (var index = 0; index < attributes.length; index++) {
  10674. var order = effect.getAttributeLocation(index);
  10675. if (order >= 0) {
  10676. var vertexBuffer = vertexBuffers[attributes[index]];
  10677. if (!vertexBuffer) {
  10678. continue;
  10679. }
  10680. this._gl.enableVertexAttribArray(order);
  10681. if (!this._vaoRecordInProgress) {
  10682. this._vertexAttribArraysEnabled[order] = true;
  10683. }
  10684. var buffer = vertexBuffer.getBuffer();
  10685. if (buffer) {
  10686. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  10687. if (vertexBuffer.getIsInstanced()) {
  10688. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  10689. if (!this._vaoRecordInProgress) {
  10690. this._currentInstanceLocations.push(order);
  10691. this._currentInstanceBuffers.push(buffer);
  10692. }
  10693. }
  10694. }
  10695. }
  10696. }
  10697. };
  10698. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  10699. var vao = this._gl.createVertexArray();
  10700. this._vaoRecordInProgress = true;
  10701. this._gl.bindVertexArray(vao);
  10702. this._mustWipeVertexAttributes = true;
  10703. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10704. this.bindIndexBuffer(indexBuffer);
  10705. this._vaoRecordInProgress = false;
  10706. this._gl.bindVertexArray(null);
  10707. return vao;
  10708. };
  10709. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  10710. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  10711. this._cachedVertexArrayObject = vertexArrayObject;
  10712. this._gl.bindVertexArray(vertexArrayObject);
  10713. this._cachedVertexBuffers = null;
  10714. this._cachedIndexBuffer = null;
  10715. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  10716. this._mustWipeVertexAttributes = true;
  10717. }
  10718. };
  10719. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  10720. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  10721. this._cachedVertexBuffers = vertexBuffer;
  10722. this._cachedEffectForVertexBuffers = effect;
  10723. var attributesCount = effect.getAttributesCount();
  10724. this._unbindVertexArrayObject();
  10725. this.unbindAllAttributes();
  10726. var offset = 0;
  10727. for (var index = 0; index < attributesCount; index++) {
  10728. if (index < vertexDeclaration.length) {
  10729. var order = effect.getAttributeLocation(index);
  10730. if (order >= 0) {
  10731. this._gl.enableVertexAttribArray(order);
  10732. this._vertexAttribArraysEnabled[order] = true;
  10733. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  10734. }
  10735. offset += vertexDeclaration[index] * 4;
  10736. }
  10737. }
  10738. }
  10739. this._bindIndexBufferWithCache(indexBuffer);
  10740. };
  10741. Engine.prototype._unbindVertexArrayObject = function () {
  10742. if (!this._cachedVertexArrayObject) {
  10743. return;
  10744. }
  10745. this._cachedVertexArrayObject = null;
  10746. this._gl.bindVertexArray(null);
  10747. };
  10748. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  10749. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  10750. this._cachedVertexBuffers = vertexBuffers;
  10751. this._cachedEffectForVertexBuffers = effect;
  10752. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10753. }
  10754. this._bindIndexBufferWithCache(indexBuffer);
  10755. };
  10756. Engine.prototype.unbindInstanceAttributes = function () {
  10757. var boundBuffer;
  10758. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  10759. var instancesBuffer = this._currentInstanceBuffers[i];
  10760. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  10761. boundBuffer = instancesBuffer;
  10762. this.bindArrayBuffer(instancesBuffer);
  10763. }
  10764. var offsetLocation = this._currentInstanceLocations[i];
  10765. this._gl.vertexAttribDivisor(offsetLocation, 0);
  10766. }
  10767. this._currentInstanceBuffers.length = 0;
  10768. this._currentInstanceLocations.length = 0;
  10769. };
  10770. Engine.prototype.releaseVertexArrayObject = function (vao) {
  10771. this._gl.deleteVertexArray(vao);
  10772. };
  10773. Engine.prototype._releaseBuffer = function (buffer) {
  10774. buffer.references--;
  10775. if (buffer.references === 0) {
  10776. this._gl.deleteBuffer(buffer);
  10777. return true;
  10778. }
  10779. return false;
  10780. };
  10781. Engine.prototype.createInstancesBuffer = function (capacity) {
  10782. var buffer = this._gl.createBuffer();
  10783. if (!buffer) {
  10784. throw new Error("Unable to create instance buffer");
  10785. }
  10786. buffer.capacity = capacity;
  10787. this.bindArrayBuffer(buffer);
  10788. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  10789. return buffer;
  10790. };
  10791. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  10792. this._gl.deleteBuffer(buffer);
  10793. };
  10794. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  10795. this.bindArrayBuffer(instancesBuffer);
  10796. if (data) {
  10797. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10798. }
  10799. if (offsetLocations[0].index !== undefined) {
  10800. var stride = 0;
  10801. for (var i = 0; i < offsetLocations.length; i++) {
  10802. var ai = offsetLocations[i];
  10803. stride += ai.attributeSize * 4;
  10804. }
  10805. for (var i = 0; i < offsetLocations.length; i++) {
  10806. var ai = offsetLocations[i];
  10807. if (!this._vertexAttribArraysEnabled[ai.index]) {
  10808. this._gl.enableVertexAttribArray(ai.index);
  10809. this._vertexAttribArraysEnabled[ai.index] = true;
  10810. }
  10811. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  10812. this._gl.vertexAttribDivisor(ai.index, 1);
  10813. this._currentInstanceLocations.push(ai.index);
  10814. this._currentInstanceBuffers.push(instancesBuffer);
  10815. }
  10816. }
  10817. else {
  10818. for (var index = 0; index < 4; index++) {
  10819. var offsetLocation = offsetLocations[index];
  10820. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  10821. this._gl.enableVertexAttribArray(offsetLocation);
  10822. this._vertexAttribArraysEnabled[offsetLocation] = true;
  10823. }
  10824. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  10825. this._gl.vertexAttribDivisor(offsetLocation, 1);
  10826. this._currentInstanceLocations.push(offsetLocation);
  10827. this._currentInstanceBuffers.push(instancesBuffer);
  10828. }
  10829. }
  10830. };
  10831. Engine.prototype.applyStates = function () {
  10832. this._depthCullingState.apply(this._gl);
  10833. this._stencilState.apply(this._gl);
  10834. this._alphaState.apply(this._gl);
  10835. };
  10836. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  10837. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  10838. };
  10839. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  10840. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  10841. };
  10842. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  10843. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  10844. };
  10845. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  10846. // Apply states
  10847. this.applyStates();
  10848. this._drawCalls.addCount(1, false);
  10849. // Render
  10850. var drawMode = this.DrawMode(fillMode);
  10851. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  10852. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  10853. if (instancesCount) {
  10854. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  10855. }
  10856. else {
  10857. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  10858. }
  10859. };
  10860. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  10861. // Apply states
  10862. this.applyStates();
  10863. this._drawCalls.addCount(1, false);
  10864. var drawMode = this.DrawMode(fillMode);
  10865. if (instancesCount) {
  10866. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  10867. }
  10868. else {
  10869. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  10870. }
  10871. };
  10872. Engine.prototype.DrawMode = function (fillMode) {
  10873. switch (fillMode) {
  10874. // Triangle views
  10875. case BABYLON.Material.TriangleFillMode:
  10876. return this._gl.TRIANGLES;
  10877. case BABYLON.Material.PointFillMode:
  10878. return this._gl.POINTS;
  10879. case BABYLON.Material.WireFrameFillMode:
  10880. return this._gl.LINES;
  10881. // Draw modes
  10882. case BABYLON.Material.PointListDrawMode:
  10883. return this._gl.POINTS;
  10884. case BABYLON.Material.LineListDrawMode:
  10885. return this._gl.LINES;
  10886. case BABYLON.Material.LineLoopDrawMode:
  10887. return this._gl.LINE_LOOP;
  10888. case BABYLON.Material.LineStripDrawMode:
  10889. return this._gl.LINE_STRIP;
  10890. case BABYLON.Material.TriangleStripDrawMode:
  10891. return this._gl.TRIANGLE_STRIP;
  10892. case BABYLON.Material.TriangleFanDrawMode:
  10893. return this._gl.TRIANGLE_FAN;
  10894. default:
  10895. return this._gl.TRIANGLES;
  10896. }
  10897. };
  10898. // Shaders
  10899. Engine.prototype._releaseEffect = function (effect) {
  10900. if (this._compiledEffects[effect._key]) {
  10901. delete this._compiledEffects[effect._key];
  10902. this._deleteProgram(effect.getProgram());
  10903. }
  10904. };
  10905. Engine.prototype._deleteProgram = function (program) {
  10906. if (program) {
  10907. program.__SPECTOR_rebuildProgram = null;
  10908. if (program.transformFeedback) {
  10909. this.deleteTransformFeedback(program.transformFeedback);
  10910. program.transformFeedback = null;
  10911. }
  10912. this._gl.deleteProgram(program);
  10913. }
  10914. };
  10915. /**
  10916. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  10917. * @param samplers An array of string used to represent textures
  10918. */
  10919. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  10920. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  10921. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  10922. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  10923. if (this._compiledEffects[name]) {
  10924. var compiledEffect = this._compiledEffects[name];
  10925. if (onCompiled && compiledEffect.isReady()) {
  10926. onCompiled(compiledEffect);
  10927. }
  10928. return compiledEffect;
  10929. }
  10930. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  10931. effect._key = name;
  10932. this._compiledEffects[name] = effect;
  10933. return effect;
  10934. };
  10935. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  10936. if (uniformsNames === void 0) { uniformsNames = []; }
  10937. if (samplers === void 0) { samplers = []; }
  10938. if (defines === void 0) { defines = ""; }
  10939. return this.createEffect({
  10940. vertex: "particles",
  10941. fragmentElement: fragmentName
  10942. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  10943. };
  10944. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  10945. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10946. context = context || this._gl;
  10947. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  10948. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  10949. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10950. };
  10951. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  10952. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10953. context = context || this._gl;
  10954. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  10955. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  10956. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  10957. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  10958. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10959. this.onAfterShaderCompilationObservable.notifyObservers(this);
  10960. return program;
  10961. };
  10962. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  10963. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10964. var shaderProgram = context.createProgram();
  10965. if (!shaderProgram) {
  10966. throw new Error("Unable to create program");
  10967. }
  10968. context.attachShader(shaderProgram, vertexShader);
  10969. context.attachShader(shaderProgram, fragmentShader);
  10970. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10971. var transformFeedback = this.createTransformFeedback();
  10972. this.bindTransformFeedback(transformFeedback);
  10973. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  10974. shaderProgram.transformFeedback = transformFeedback;
  10975. }
  10976. context.linkProgram(shaderProgram);
  10977. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10978. this.bindTransformFeedback(null);
  10979. }
  10980. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  10981. if (!linked) {
  10982. context.validateProgram(shaderProgram);
  10983. var error = context.getProgramInfoLog(shaderProgram);
  10984. if (error) {
  10985. throw new Error(error);
  10986. }
  10987. }
  10988. context.deleteShader(vertexShader);
  10989. context.deleteShader(fragmentShader);
  10990. return shaderProgram;
  10991. };
  10992. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  10993. var results = new Array();
  10994. for (var index = 0; index < uniformsNames.length; index++) {
  10995. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  10996. }
  10997. return results;
  10998. };
  10999. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11000. var results = [];
  11001. for (var index = 0; index < attributesNames.length; index++) {
  11002. try {
  11003. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11004. }
  11005. catch (e) {
  11006. results.push(-1);
  11007. }
  11008. }
  11009. return results;
  11010. };
  11011. Engine.prototype.enableEffect = function (effect) {
  11012. if (!effect) {
  11013. return;
  11014. }
  11015. // Use program
  11016. this.bindSamplers(effect);
  11017. this._currentEffect = effect;
  11018. if (effect.onBind) {
  11019. effect.onBind(effect);
  11020. }
  11021. effect.onBindObservable.notifyObservers(effect);
  11022. };
  11023. Engine.prototype.setIntArray = function (uniform, array) {
  11024. if (!uniform)
  11025. return;
  11026. this._gl.uniform1iv(uniform, array);
  11027. };
  11028. Engine.prototype.setIntArray2 = function (uniform, array) {
  11029. if (!uniform || array.length % 2 !== 0)
  11030. return;
  11031. this._gl.uniform2iv(uniform, array);
  11032. };
  11033. Engine.prototype.setIntArray3 = function (uniform, array) {
  11034. if (!uniform || array.length % 3 !== 0)
  11035. return;
  11036. this._gl.uniform3iv(uniform, array);
  11037. };
  11038. Engine.prototype.setIntArray4 = function (uniform, array) {
  11039. if (!uniform || array.length % 4 !== 0)
  11040. return;
  11041. this._gl.uniform4iv(uniform, array);
  11042. };
  11043. Engine.prototype.setFloatArray = function (uniform, array) {
  11044. if (!uniform)
  11045. return;
  11046. this._gl.uniform1fv(uniform, array);
  11047. };
  11048. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11049. if (!uniform || array.length % 2 !== 0)
  11050. return;
  11051. this._gl.uniform2fv(uniform, array);
  11052. };
  11053. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11054. if (!uniform || array.length % 3 !== 0)
  11055. return;
  11056. this._gl.uniform3fv(uniform, array);
  11057. };
  11058. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11059. if (!uniform || array.length % 4 !== 0)
  11060. return;
  11061. this._gl.uniform4fv(uniform, array);
  11062. };
  11063. Engine.prototype.setArray = function (uniform, array) {
  11064. if (!uniform)
  11065. return;
  11066. this._gl.uniform1fv(uniform, array);
  11067. };
  11068. Engine.prototype.setArray2 = function (uniform, array) {
  11069. if (!uniform || array.length % 2 !== 0)
  11070. return;
  11071. this._gl.uniform2fv(uniform, array);
  11072. };
  11073. Engine.prototype.setArray3 = function (uniform, array) {
  11074. if (!uniform || array.length % 3 !== 0)
  11075. return;
  11076. this._gl.uniform3fv(uniform, array);
  11077. };
  11078. Engine.prototype.setArray4 = function (uniform, array) {
  11079. if (!uniform || array.length % 4 !== 0)
  11080. return;
  11081. this._gl.uniform4fv(uniform, array);
  11082. };
  11083. Engine.prototype.setMatrices = function (uniform, matrices) {
  11084. if (!uniform)
  11085. return;
  11086. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11087. };
  11088. Engine.prototype.setMatrix = function (uniform, matrix) {
  11089. if (!uniform)
  11090. return;
  11091. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11092. };
  11093. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11094. if (!uniform)
  11095. return;
  11096. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11097. };
  11098. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11099. if (!uniform)
  11100. return;
  11101. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11102. };
  11103. Engine.prototype.setInt = function (uniform, value) {
  11104. if (!uniform)
  11105. return;
  11106. this._gl.uniform1i(uniform, value);
  11107. };
  11108. Engine.prototype.setFloat = function (uniform, value) {
  11109. if (!uniform)
  11110. return;
  11111. this._gl.uniform1f(uniform, value);
  11112. };
  11113. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11114. if (!uniform)
  11115. return;
  11116. this._gl.uniform2f(uniform, x, y);
  11117. };
  11118. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11119. if (!uniform)
  11120. return;
  11121. this._gl.uniform3f(uniform, x, y, z);
  11122. };
  11123. Engine.prototype.setBool = function (uniform, bool) {
  11124. if (!uniform)
  11125. return;
  11126. this._gl.uniform1i(uniform, bool);
  11127. };
  11128. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11129. if (!uniform)
  11130. return;
  11131. this._gl.uniform4f(uniform, x, y, z, w);
  11132. };
  11133. Engine.prototype.setColor3 = function (uniform, color3) {
  11134. if (!uniform)
  11135. return;
  11136. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11137. };
  11138. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11139. if (!uniform)
  11140. return;
  11141. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11142. };
  11143. // States
  11144. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11145. if (zOffset === void 0) { zOffset = 0; }
  11146. if (reverseSide === void 0) { reverseSide = false; }
  11147. // Culling
  11148. if (this._depthCullingState.cull !== culling || force) {
  11149. this._depthCullingState.cull = culling;
  11150. }
  11151. // Cull face
  11152. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11153. if (this._depthCullingState.cullFace !== cullFace || force) {
  11154. this._depthCullingState.cullFace = cullFace;
  11155. }
  11156. // Z offset
  11157. this.setZOffset(zOffset);
  11158. // Front face
  11159. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11160. if (this._depthCullingState.frontFace !== frontFace || force) {
  11161. this._depthCullingState.frontFace = frontFace;
  11162. }
  11163. };
  11164. Engine.prototype.setZOffset = function (value) {
  11165. this._depthCullingState.zOffset = value;
  11166. };
  11167. Engine.prototype.getZOffset = function () {
  11168. return this._depthCullingState.zOffset;
  11169. };
  11170. Engine.prototype.setDepthBuffer = function (enable) {
  11171. this._depthCullingState.depthTest = enable;
  11172. };
  11173. Engine.prototype.getDepthWrite = function () {
  11174. return this._depthCullingState.depthMask;
  11175. };
  11176. Engine.prototype.setDepthWrite = function (enable) {
  11177. this._depthCullingState.depthMask = enable;
  11178. };
  11179. Engine.prototype.setColorWrite = function (enable) {
  11180. this._gl.colorMask(enable, enable, enable, enable);
  11181. this._colorWrite = enable;
  11182. };
  11183. Engine.prototype.getColorWrite = function () {
  11184. return this._colorWrite;
  11185. };
  11186. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11187. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11188. };
  11189. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11190. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11191. if (this._alphaMode === mode) {
  11192. return;
  11193. }
  11194. switch (mode) {
  11195. case Engine.ALPHA_DISABLE:
  11196. this._alphaState.alphaBlend = false;
  11197. break;
  11198. case Engine.ALPHA_PREMULTIPLIED:
  11199. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11200. this._alphaState.alphaBlend = true;
  11201. break;
  11202. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11203. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11204. this._alphaState.alphaBlend = true;
  11205. break;
  11206. case Engine.ALPHA_COMBINE:
  11207. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11208. this._alphaState.alphaBlend = true;
  11209. break;
  11210. case Engine.ALPHA_ONEONE:
  11211. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11212. this._alphaState.alphaBlend = true;
  11213. break;
  11214. case Engine.ALPHA_ADD:
  11215. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11216. this._alphaState.alphaBlend = true;
  11217. break;
  11218. case Engine.ALPHA_SUBTRACT:
  11219. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11220. this._alphaState.alphaBlend = true;
  11221. break;
  11222. case Engine.ALPHA_MULTIPLY:
  11223. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11224. this._alphaState.alphaBlend = true;
  11225. break;
  11226. case Engine.ALPHA_MAXIMIZED:
  11227. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11228. this._alphaState.alphaBlend = true;
  11229. break;
  11230. case Engine.ALPHA_INTERPOLATE:
  11231. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11232. this._alphaState.alphaBlend = true;
  11233. break;
  11234. case Engine.ALPHA_SCREENMODE:
  11235. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11236. this._alphaState.alphaBlend = true;
  11237. break;
  11238. }
  11239. if (!noDepthWriteChange) {
  11240. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11241. }
  11242. this._alphaMode = mode;
  11243. };
  11244. Engine.prototype.getAlphaMode = function () {
  11245. return this._alphaMode;
  11246. };
  11247. Engine.prototype.setAlphaTesting = function (enable) {
  11248. this._alphaTest = enable;
  11249. };
  11250. Engine.prototype.getAlphaTesting = function () {
  11251. return !!this._alphaTest;
  11252. };
  11253. // Textures
  11254. Engine.prototype.wipeCaches = function (bruteForce) {
  11255. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11256. return;
  11257. }
  11258. this._currentEffect = null;
  11259. // 6/8/2017: deltakosh: Should not be required anymore.
  11260. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11261. if (bruteForce) {
  11262. this.resetTextureCache();
  11263. this._currentProgram = null;
  11264. this._stencilState.reset();
  11265. this._depthCullingState.reset();
  11266. this.setDepthFunctionToLessOrEqual();
  11267. this._alphaState.reset();
  11268. }
  11269. this._resetVertexBufferBinding();
  11270. this._cachedIndexBuffer = null;
  11271. this._cachedEffectForVertexBuffers = null;
  11272. this._unbindVertexArrayObject();
  11273. this.bindIndexBuffer(null);
  11274. };
  11275. /**
  11276. * Set the compressed texture format to use, based on the formats you have, and the formats
  11277. * supported by the hardware / browser.
  11278. *
  11279. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11280. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11281. * to API arguments needed to compressed textures. This puts the burden on the container
  11282. * generator to house the arcane code for determining these for current & future formats.
  11283. *
  11284. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11285. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11286. *
  11287. * Note: The result of this call is not taken into account when a texture is base64.
  11288. *
  11289. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11290. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11291. *
  11292. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11293. * @returns The extension selected.
  11294. */
  11295. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11296. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11297. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11298. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11299. return this._textureFormatInUse = this._texturesSupported[i];
  11300. }
  11301. }
  11302. }
  11303. // actively set format to nothing, to allow this to be called more than once
  11304. // and possibly fail the 2nd time
  11305. this._textureFormatInUse = null;
  11306. return null;
  11307. };
  11308. Engine.prototype._createTexture = function () {
  11309. var texture = this._gl.createTexture();
  11310. if (!texture) {
  11311. throw new Error("Unable to create texture");
  11312. }
  11313. return texture;
  11314. };
  11315. /**
  11316. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11317. * @param {string} urlArg- This contains one of the following:
  11318. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11319. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11320. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11321. *
  11322. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11323. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11324. * @param {Scene} scene- Needed for loading to the correct scene.
  11325. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11326. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11327. * @param {callback} onError- Optional callback to be called upon failure.
  11328. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11329. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11330. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11331. *
  11332. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11333. */
  11334. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11335. var _this = this;
  11336. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11337. if (onLoad === void 0) { onLoad = null; }
  11338. if (onError === void 0) { onError = null; }
  11339. if (buffer === void 0) { buffer = null; }
  11340. if (fallBack === void 0) { fallBack = null; }
  11341. if (format === void 0) { format = null; }
  11342. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11343. var fromData = url.substr(0, 5) === "data:";
  11344. var fromBlob = url.substr(0, 5) === "blob:";
  11345. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11346. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11347. // establish the file extension, if possible
  11348. var lastDot = url.lastIndexOf('.');
  11349. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11350. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  11351. var isTGA = (extension === ".tga");
  11352. // determine if a ktx file should be substituted
  11353. var isKTX = false;
  11354. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11355. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11356. isKTX = true;
  11357. }
  11358. if (scene) {
  11359. scene._addPendingData(texture);
  11360. }
  11361. texture.url = url;
  11362. texture.generateMipMaps = !noMipmap;
  11363. texture.samplingMode = samplingMode;
  11364. texture.invertY = invertY;
  11365. if (!this._doNotHandleContextLost) {
  11366. // Keep a link to the buffer only if we plan to handle context lost
  11367. texture._buffer = buffer;
  11368. }
  11369. var onLoadObserver = null;
  11370. if (onLoad && !fallBack) {
  11371. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11372. }
  11373. if (!fallBack)
  11374. this._internalTexturesCache.push(texture);
  11375. var onerror = function (message, exception) {
  11376. if (scene) {
  11377. scene._removePendingData(texture);
  11378. }
  11379. if (onLoadObserver) {
  11380. texture.onLoadedObservable.remove(onLoadObserver);
  11381. }
  11382. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11383. if (isKTX) {
  11384. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11385. }
  11386. else if (BABYLON.Tools.UseFallbackTexture) {
  11387. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11388. }
  11389. if (onError) {
  11390. onError(message || "Unknown error", exception);
  11391. }
  11392. };
  11393. var callback = null;
  11394. // processing for non-image formats
  11395. if (isKTX || isTGA || isDDS) {
  11396. if (isKTX) {
  11397. callback = function (data) {
  11398. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11399. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11400. ktx.uploadLevels(_this._gl, !noMipmap);
  11401. return false;
  11402. }, samplingMode);
  11403. };
  11404. }
  11405. else if (isTGA) {
  11406. callback = function (arrayBuffer) {
  11407. var data = new Uint8Array(arrayBuffer);
  11408. var header = BABYLON.TGATools.GetTGAHeader(data);
  11409. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11410. BABYLON.TGATools.UploadContent(_this._gl, data);
  11411. return false;
  11412. }, samplingMode);
  11413. };
  11414. }
  11415. else if (isDDS) {
  11416. callback = function (data) {
  11417. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11418. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11419. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11420. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11421. return false;
  11422. }, samplingMode);
  11423. };
  11424. }
  11425. if (!buffer) {
  11426. this._loadFile(url, function (data) {
  11427. if (callback) {
  11428. callback(data);
  11429. }
  11430. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11431. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11432. });
  11433. }
  11434. else {
  11435. if (callback) {
  11436. callback(buffer);
  11437. }
  11438. }
  11439. // image format processing
  11440. }
  11441. else {
  11442. var onload = function (img) {
  11443. if (fromBlob && !_this._doNotHandleContextLost) {
  11444. // We need to store the image if we need to rebuild the texture
  11445. // in case of a webgl context lost
  11446. texture._buffer = img;
  11447. }
  11448. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  11449. var gl = _this._gl;
  11450. var isPot = (img.width === potWidth && img.height === potHeight);
  11451. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  11452. if (isPot) {
  11453. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11454. return false;
  11455. }
  11456. // Using shaders to rescale because canvas.drawImage is lossy
  11457. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11458. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  11459. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11460. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11461. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11462. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11463. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11464. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  11465. _this._releaseTexture(source);
  11466. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11467. continuationCallback();
  11468. });
  11469. return true;
  11470. }, samplingMode);
  11471. };
  11472. if (!fromData || isBase64)
  11473. if (buffer instanceof HTMLImageElement) {
  11474. onload(buffer);
  11475. }
  11476. else {
  11477. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11478. }
  11479. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  11480. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  11481. else
  11482. onload(buffer);
  11483. }
  11484. return texture;
  11485. };
  11486. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  11487. var _this = this;
  11488. var rtt = this.createRenderTargetTexture({
  11489. width: destination.width,
  11490. height: destination.height,
  11491. }, {
  11492. generateMipMaps: false,
  11493. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  11494. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  11495. generateDepthBuffer: false,
  11496. generateStencilBuffer: false
  11497. });
  11498. if (!this._rescalePostProcess) {
  11499. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  11500. }
  11501. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  11502. _this._rescalePostProcess.onApply = function (effect) {
  11503. effect._bindTexture("textureSampler", source);
  11504. };
  11505. var hostingScene = scene;
  11506. if (!hostingScene) {
  11507. hostingScene = _this.scenes[_this.scenes.length - 1];
  11508. }
  11509. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  11510. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  11511. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  11512. _this.unBindFramebuffer(rtt);
  11513. _this._releaseTexture(rtt);
  11514. if (onComplete) {
  11515. onComplete();
  11516. }
  11517. });
  11518. };
  11519. Engine.prototype._getInternalFormat = function (format) {
  11520. var internalFormat = this._gl.RGBA;
  11521. switch (format) {
  11522. case Engine.TEXTUREFORMAT_ALPHA:
  11523. internalFormat = this._gl.ALPHA;
  11524. break;
  11525. case Engine.TEXTUREFORMAT_LUMINANCE:
  11526. internalFormat = this._gl.LUMINANCE;
  11527. break;
  11528. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  11529. internalFormat = this._gl.LUMINANCE_ALPHA;
  11530. break;
  11531. case Engine.TEXTUREFORMAT_RGB:
  11532. internalFormat = this._gl.RGB;
  11533. break;
  11534. case Engine.TEXTUREFORMAT_RGBA:
  11535. internalFormat = this._gl.RGBA;
  11536. break;
  11537. }
  11538. return internalFormat;
  11539. };
  11540. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  11541. if (compression === void 0) { compression = null; }
  11542. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11543. if (!texture) {
  11544. return;
  11545. }
  11546. var internalFormat = this._getInternalFormat(format);
  11547. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11548. var textureType = this._getWebGLTextureType(type);
  11549. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11550. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11551. if (!this._doNotHandleContextLost) {
  11552. texture._bufferView = data;
  11553. texture.format = format;
  11554. texture.type = type;
  11555. texture.invertY = invertY;
  11556. texture._compression = compression;
  11557. }
  11558. if (texture.width % 4 !== 0) {
  11559. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11560. }
  11561. if (compression && data) {
  11562. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  11563. }
  11564. else {
  11565. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  11566. }
  11567. if (texture.generateMipMaps) {
  11568. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11569. }
  11570. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11571. // this.resetTextureCache();
  11572. texture.isReady = true;
  11573. };
  11574. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  11575. if (compression === void 0) { compression = null; }
  11576. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11577. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  11578. texture.baseWidth = width;
  11579. texture.baseHeight = height;
  11580. texture.width = width;
  11581. texture.height = height;
  11582. texture.format = format;
  11583. texture.generateMipMaps = generateMipMaps;
  11584. texture.samplingMode = samplingMode;
  11585. texture.invertY = invertY;
  11586. texture._compression = compression;
  11587. texture.type = type;
  11588. if (!this._doNotHandleContextLost) {
  11589. texture._bufferView = data;
  11590. }
  11591. this.updateRawTexture(texture, data, format, invertY, compression, type);
  11592. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11593. // Filters
  11594. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11595. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11596. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11597. if (generateMipMaps) {
  11598. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11599. }
  11600. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11601. this._internalTexturesCache.push(texture);
  11602. return texture;
  11603. };
  11604. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  11605. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  11606. texture.baseWidth = width;
  11607. texture.baseHeight = height;
  11608. if (generateMipMaps) {
  11609. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  11610. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  11611. }
  11612. // this.resetTextureCache();
  11613. texture.width = width;
  11614. texture.height = height;
  11615. texture.isReady = false;
  11616. texture.generateMipMaps = generateMipMaps;
  11617. texture.samplingMode = samplingMode;
  11618. this.updateTextureSamplingMode(samplingMode, texture);
  11619. this._internalTexturesCache.push(texture);
  11620. return texture;
  11621. };
  11622. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  11623. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  11624. if (texture.isCube) {
  11625. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11626. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11627. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11628. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11629. }
  11630. else if (texture.is3D) {
  11631. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11632. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11633. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11634. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11635. }
  11636. else {
  11637. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11638. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11639. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11640. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11641. }
  11642. texture.samplingMode = samplingMode;
  11643. };
  11644. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  11645. if (premulAlpha === void 0) { premulAlpha = false; }
  11646. if (!texture) {
  11647. return;
  11648. }
  11649. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11650. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  11651. if (premulAlpha) {
  11652. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  11653. }
  11654. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  11655. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  11656. if (texture.generateMipMaps) {
  11657. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11658. }
  11659. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11660. if (premulAlpha) {
  11661. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  11662. }
  11663. texture.isReady = true;
  11664. };
  11665. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  11666. if (!texture || texture._isDisabled) {
  11667. return;
  11668. }
  11669. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11670. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  11671. try {
  11672. // Testing video texture support
  11673. if (this._videoTextureSupported === undefined) {
  11674. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11675. if (this._gl.getError() !== 0) {
  11676. this._videoTextureSupported = false;
  11677. }
  11678. else {
  11679. this._videoTextureSupported = true;
  11680. }
  11681. }
  11682. // Copy video through the current working canvas if video texture is not supported
  11683. if (!this._videoTextureSupported) {
  11684. if (!texture._workingCanvas) {
  11685. texture._workingCanvas = document.createElement("canvas");
  11686. var context = texture._workingCanvas.getContext("2d");
  11687. if (!context) {
  11688. throw new Error("Unable to get 2d context");
  11689. }
  11690. texture._workingContext = context;
  11691. texture._workingCanvas.width = texture.width;
  11692. texture._workingCanvas.height = texture.height;
  11693. }
  11694. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  11695. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  11696. }
  11697. else {
  11698. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11699. }
  11700. if (texture.generateMipMaps) {
  11701. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11702. }
  11703. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11704. // this.resetTextureCache();
  11705. texture.isReady = true;
  11706. }
  11707. catch (ex) {
  11708. // Something unexpected
  11709. // Let's disable the texture
  11710. texture._isDisabled = true;
  11711. }
  11712. };
  11713. Engine.prototype.createRenderTargetTexture = function (size, options) {
  11714. var fullOptions = new RenderTargetCreationOptions();
  11715. if (options !== undefined && typeof options === "object") {
  11716. fullOptions.generateMipMaps = options.generateMipMaps;
  11717. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11718. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  11719. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  11720. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  11721. }
  11722. else {
  11723. fullOptions.generateMipMaps = options;
  11724. fullOptions.generateDepthBuffer = true;
  11725. fullOptions.generateStencilBuffer = false;
  11726. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11727. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11728. }
  11729. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11730. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11731. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11732. }
  11733. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11734. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11735. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11736. }
  11737. var gl = this._gl;
  11738. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11739. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11740. var width = size.width || size;
  11741. var height = size.height || size;
  11742. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  11743. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11744. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11745. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11746. }
  11747. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11748. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11749. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11750. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11751. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  11752. // Create the framebuffer
  11753. var framebuffer = gl.createFramebuffer();
  11754. this.bindUnboundFramebuffer(framebuffer);
  11755. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11756. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  11757. if (fullOptions.generateMipMaps) {
  11758. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11759. }
  11760. // Unbind
  11761. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11762. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11763. this.bindUnboundFramebuffer(null);
  11764. texture._framebuffer = framebuffer;
  11765. texture.baseWidth = width;
  11766. texture.baseHeight = height;
  11767. texture.width = width;
  11768. texture.height = height;
  11769. texture.isReady = true;
  11770. texture.samples = 1;
  11771. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  11772. texture.samplingMode = fullOptions.samplingMode;
  11773. texture.type = fullOptions.type;
  11774. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  11775. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  11776. // this.resetTextureCache();
  11777. this._internalTexturesCache.push(texture);
  11778. return texture;
  11779. };
  11780. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  11781. var generateMipMaps = false;
  11782. var generateDepthBuffer = true;
  11783. var generateStencilBuffer = false;
  11784. var generateDepthTexture = false;
  11785. var textureCount = 1;
  11786. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  11787. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11788. var types = [], samplingModes = [];
  11789. if (options !== undefined) {
  11790. generateMipMaps = options.generateMipMaps;
  11791. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11792. generateStencilBuffer = options.generateStencilBuffer;
  11793. generateDepthTexture = options.generateDepthTexture;
  11794. textureCount = options.textureCount || 1;
  11795. if (options.types) {
  11796. types = options.types;
  11797. }
  11798. if (options.samplingModes) {
  11799. samplingModes = options.samplingModes;
  11800. }
  11801. }
  11802. var gl = this._gl;
  11803. // Create the framebuffer
  11804. var framebuffer = gl.createFramebuffer();
  11805. this.bindUnboundFramebuffer(framebuffer);
  11806. var width = size.width || size;
  11807. var height = size.height || size;
  11808. var textures = [];
  11809. var attachments = [];
  11810. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  11811. for (var i = 0; i < textureCount; i++) {
  11812. var samplingMode = samplingModes[i] || defaultSamplingMode;
  11813. var type = types[i] || defaultType;
  11814. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11815. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11816. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11817. }
  11818. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11819. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11820. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11821. }
  11822. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11823. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11824. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11825. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11826. }
  11827. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11828. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11829. textures.push(texture);
  11830. attachments.push(attachment);
  11831. gl.activeTexture(gl["TEXTURE" + i]);
  11832. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  11833. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11834. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11835. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11836. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11837. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11838. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11839. if (generateMipMaps) {
  11840. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11841. }
  11842. // Unbind
  11843. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11844. texture._framebuffer = framebuffer;
  11845. texture._depthStencilBuffer = depthStencilBuffer;
  11846. texture.baseWidth = width;
  11847. texture.baseHeight = height;
  11848. texture.width = width;
  11849. texture.height = height;
  11850. texture.isReady = true;
  11851. texture.samples = 1;
  11852. texture.generateMipMaps = generateMipMaps;
  11853. texture.samplingMode = samplingMode;
  11854. texture.type = type;
  11855. texture._generateDepthBuffer = generateDepthBuffer;
  11856. texture._generateStencilBuffer = generateStencilBuffer;
  11857. texture._attachments = attachments;
  11858. this._internalTexturesCache.push(texture);
  11859. }
  11860. if (generateDepthTexture && this._caps.depthTextureExtension) {
  11861. // Depth texture
  11862. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11863. gl.activeTexture(gl.TEXTURE0);
  11864. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  11865. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11866. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11867. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11868. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11869. 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);
  11870. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  11871. depthTexture._framebuffer = framebuffer;
  11872. depthTexture.baseWidth = width;
  11873. depthTexture.baseHeight = height;
  11874. depthTexture.width = width;
  11875. depthTexture.height = height;
  11876. depthTexture.isReady = true;
  11877. depthTexture.samples = 1;
  11878. depthTexture.generateMipMaps = generateMipMaps;
  11879. depthTexture.samplingMode = gl.NEAREST;
  11880. depthTexture._generateDepthBuffer = generateDepthBuffer;
  11881. depthTexture._generateStencilBuffer = generateStencilBuffer;
  11882. textures.push(depthTexture);
  11883. this._internalTexturesCache.push(depthTexture);
  11884. }
  11885. gl.drawBuffers(attachments);
  11886. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11887. this.bindUnboundFramebuffer(null);
  11888. this.resetTextureCache();
  11889. return textures;
  11890. };
  11891. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  11892. if (samples === void 0) { samples = 1; }
  11893. var depthStencilBuffer = null;
  11894. var gl = this._gl;
  11895. // Create the depth/stencil buffer
  11896. if (generateStencilBuffer) {
  11897. depthStencilBuffer = gl.createRenderbuffer();
  11898. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11899. if (samples > 1) {
  11900. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  11901. }
  11902. else {
  11903. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  11904. }
  11905. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11906. }
  11907. else if (generateDepthBuffer) {
  11908. depthStencilBuffer = gl.createRenderbuffer();
  11909. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11910. if (samples > 1) {
  11911. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  11912. }
  11913. else {
  11914. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  11915. }
  11916. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11917. }
  11918. return depthStencilBuffer;
  11919. };
  11920. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  11921. if (this.webGLVersion < 2 || !texture) {
  11922. return 1;
  11923. }
  11924. if (texture.samples === samples) {
  11925. return samples;
  11926. }
  11927. var gl = this._gl;
  11928. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11929. // Dispose previous render buffers
  11930. if (texture._depthStencilBuffer) {
  11931. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11932. texture._depthStencilBuffer = null;
  11933. }
  11934. if (texture._MSAAFramebuffer) {
  11935. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11936. texture._MSAAFramebuffer = null;
  11937. }
  11938. if (texture._MSAARenderBuffer) {
  11939. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11940. texture._MSAARenderBuffer = null;
  11941. }
  11942. if (samples > 1) {
  11943. var framebuffer = gl.createFramebuffer();
  11944. if (!framebuffer) {
  11945. throw new Error("Unable to create multi sampled framebuffer");
  11946. }
  11947. texture._MSAAFramebuffer = framebuffer;
  11948. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  11949. var colorRenderbuffer = gl.createRenderbuffer();
  11950. if (!colorRenderbuffer) {
  11951. throw new Error("Unable to create multi sampled framebuffer");
  11952. }
  11953. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11954. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  11955. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  11956. texture._MSAARenderBuffer = colorRenderbuffer;
  11957. }
  11958. else {
  11959. this.bindUnboundFramebuffer(texture._framebuffer);
  11960. }
  11961. texture.samples = samples;
  11962. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  11963. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11964. this.bindUnboundFramebuffer(null);
  11965. return samples;
  11966. };
  11967. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  11968. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  11969. return 1;
  11970. }
  11971. if (textures[0].samples === samples) {
  11972. return samples;
  11973. }
  11974. var gl = this._gl;
  11975. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11976. // Dispose previous render buffers
  11977. if (textures[0]._depthStencilBuffer) {
  11978. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  11979. textures[0]._depthStencilBuffer = null;
  11980. }
  11981. if (textures[0]._MSAAFramebuffer) {
  11982. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  11983. textures[0]._MSAAFramebuffer = null;
  11984. }
  11985. for (var i = 0; i < textures.length; i++) {
  11986. if (textures[i]._MSAARenderBuffer) {
  11987. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  11988. textures[i]._MSAARenderBuffer = null;
  11989. }
  11990. }
  11991. if (samples > 1) {
  11992. var framebuffer = gl.createFramebuffer();
  11993. if (!framebuffer) {
  11994. throw new Error("Unable to create multi sampled framebuffer");
  11995. }
  11996. this.bindUnboundFramebuffer(framebuffer);
  11997. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  11998. var attachments = [];
  11999. for (var i = 0; i < textures.length; i++) {
  12000. var texture = textures[i];
  12001. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12002. var colorRenderbuffer = gl.createRenderbuffer();
  12003. if (!colorRenderbuffer) {
  12004. throw new Error("Unable to create multi sampled framebuffer");
  12005. }
  12006. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12007. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12008. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12009. texture._MSAAFramebuffer = framebuffer;
  12010. texture._MSAARenderBuffer = colorRenderbuffer;
  12011. texture.samples = samples;
  12012. texture._depthStencilBuffer = depthStencilBuffer;
  12013. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12014. attachments.push(attachment);
  12015. }
  12016. gl.drawBuffers(attachments);
  12017. }
  12018. else {
  12019. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12020. }
  12021. this.bindUnboundFramebuffer(null);
  12022. return samples;
  12023. };
  12024. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12025. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12026. };
  12027. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12028. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12029. };
  12030. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12031. var gl = this._gl;
  12032. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12033. var generateMipMaps = true;
  12034. var generateDepthBuffer = true;
  12035. var generateStencilBuffer = false;
  12036. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12037. if (options !== undefined) {
  12038. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12039. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12040. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12041. if (options.samplingMode !== undefined) {
  12042. samplingMode = options.samplingMode;
  12043. }
  12044. }
  12045. texture.isCube = true;
  12046. texture.generateMipMaps = generateMipMaps;
  12047. texture.samples = 1;
  12048. texture.samplingMode = samplingMode;
  12049. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12050. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12051. for (var face = 0; face < 6; face++) {
  12052. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12053. }
  12054. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12055. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12056. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12057. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12058. // Create the framebuffer
  12059. var framebuffer = gl.createFramebuffer();
  12060. this.bindUnboundFramebuffer(framebuffer);
  12061. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12062. // Mipmaps
  12063. if (texture.generateMipMaps) {
  12064. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12065. }
  12066. // Unbind
  12067. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12068. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12069. this.bindUnboundFramebuffer(null);
  12070. texture._framebuffer = framebuffer;
  12071. texture.width = size;
  12072. texture.height = size;
  12073. texture.isReady = true;
  12074. //this.resetTextureCache();
  12075. this._internalTexturesCache.push(texture);
  12076. return texture;
  12077. };
  12078. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12079. var _this = this;
  12080. if (onLoad === void 0) { onLoad = null; }
  12081. if (onError === void 0) { onError = null; }
  12082. if (forcedExtension === void 0) { forcedExtension = null; }
  12083. var callback = function (loadData) {
  12084. if (!loadData) {
  12085. if (onLoad) {
  12086. onLoad(null);
  12087. }
  12088. return;
  12089. }
  12090. var texture = loadData.texture;
  12091. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12092. texture._lodGenerationScale = scale;
  12093. texture._lodGenerationOffset = offset;
  12094. if (_this._caps.textureLOD) {
  12095. // Do not add extra process if texture lod is supported.
  12096. if (onLoad) {
  12097. onLoad(texture);
  12098. }
  12099. return;
  12100. }
  12101. var mipSlices = 3;
  12102. var gl = _this._gl;
  12103. var width = loadData.width;
  12104. if (!width) {
  12105. return;
  12106. }
  12107. var textures = [];
  12108. for (var i = 0; i < mipSlices; i++) {
  12109. //compute LOD from even spacing in smoothness (matching shader calculation)
  12110. var smoothness = i / (mipSlices - 1);
  12111. var roughness = 1 - smoothness;
  12112. var minLODIndex = offset; // roughness = 0
  12113. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12114. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12115. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12116. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12117. glTextureFromLod.isCube = true;
  12118. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12119. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12120. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12121. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12122. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12123. if (loadData.isDDS) {
  12124. var info = loadData.info;
  12125. var data = loadData.data;
  12126. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12127. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12128. }
  12129. else {
  12130. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12131. }
  12132. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12133. // Wrap in a base texture for easy binding.
  12134. var lodTexture = new BABYLON.BaseTexture(scene);
  12135. lodTexture.isCube = true;
  12136. lodTexture._texture = glTextureFromLod;
  12137. glTextureFromLod.isReady = true;
  12138. textures.push(lodTexture);
  12139. }
  12140. texture._lodTextureHigh = textures[2];
  12141. texture._lodTextureMid = textures[1];
  12142. texture._lodTextureLow = textures[0];
  12143. if (onLoad) {
  12144. onLoad(texture);
  12145. }
  12146. };
  12147. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12148. };
  12149. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12150. var _this = this;
  12151. if (onLoad === void 0) { onLoad = null; }
  12152. if (onError === void 0) { onError = null; }
  12153. if (forcedExtension === void 0) { forcedExtension = null; }
  12154. var gl = this._gl;
  12155. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12156. texture.isCube = true;
  12157. texture.url = rootUrl;
  12158. texture.generateMipMaps = !noMipmap;
  12159. if (!this._doNotHandleContextLost) {
  12160. texture._extension = forcedExtension;
  12161. texture._files = files;
  12162. }
  12163. var isKTX = false;
  12164. var isDDS = false;
  12165. var lastDot = rootUrl.lastIndexOf('.');
  12166. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12167. if (this._textureFormatInUse) {
  12168. extension = this._textureFormatInUse;
  12169. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12170. isKTX = true;
  12171. }
  12172. else {
  12173. isDDS = (extension === ".dds");
  12174. }
  12175. var onerror = function (request, exception) {
  12176. if (onError && request) {
  12177. onError(request.status + " " + request.statusText, exception);
  12178. }
  12179. };
  12180. if (isKTX) {
  12181. this._loadFile(rootUrl, function (data) {
  12182. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12183. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12184. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12185. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12186. ktx.uploadLevels(_this._gl, !noMipmap);
  12187. _this.setCubeMapTextureParams(gl, loadMipmap);
  12188. texture.width = ktx.pixelWidth;
  12189. texture.height = ktx.pixelHeight;
  12190. texture.isReady = true;
  12191. }, undefined, undefined, true, onerror);
  12192. }
  12193. else if (isDDS) {
  12194. if (files && files.length === 6) {
  12195. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12196. var info;
  12197. var loadMipmap = false;
  12198. var width = 0;
  12199. for (var index = 0; index < imgs.length; index++) {
  12200. var data = imgs[index];
  12201. info = BABYLON.DDSTools.GetDDSInfo(data);
  12202. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12203. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12204. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12205. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12206. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12207. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12208. }
  12209. texture.width = info.width;
  12210. texture.height = info.height;
  12211. texture.type = info.textureType;
  12212. width = info.width;
  12213. }
  12214. _this.setCubeMapTextureParams(gl, loadMipmap);
  12215. texture.isReady = true;
  12216. if (onLoad) {
  12217. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12218. }
  12219. }, files, onError);
  12220. }
  12221. else {
  12222. this._loadFile(rootUrl, function (data) {
  12223. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12224. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12225. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12226. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12227. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12228. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12229. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12230. }
  12231. _this.setCubeMapTextureParams(gl, loadMipmap);
  12232. texture.width = info.width;
  12233. texture.height = info.height;
  12234. texture.isReady = true;
  12235. texture.type = info.textureType;
  12236. if (onLoad) {
  12237. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12238. }
  12239. }, undefined, undefined, true, onerror);
  12240. }
  12241. }
  12242. else {
  12243. if (!files) {
  12244. throw new Error("Cannot load cubemap because files were not defined");
  12245. }
  12246. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12247. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12248. var height = width;
  12249. _this._prepareWorkingCanvas();
  12250. if (!_this._workingCanvas || !_this._workingContext) {
  12251. return;
  12252. }
  12253. _this._workingCanvas.width = width;
  12254. _this._workingCanvas.height = height;
  12255. var faces = [
  12256. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12257. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12258. ];
  12259. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12260. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12261. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12262. for (var index = 0; index < faces.length; index++) {
  12263. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12264. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12265. }
  12266. if (!noMipmap) {
  12267. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12268. }
  12269. _this.setCubeMapTextureParams(gl, !noMipmap);
  12270. texture.width = width;
  12271. texture.height = height;
  12272. texture.isReady = true;
  12273. if (format) {
  12274. texture.format = format;
  12275. }
  12276. texture.onLoadedObservable.notifyObservers(texture);
  12277. texture.onLoadedObservable.clear();
  12278. if (onLoad) {
  12279. onLoad();
  12280. }
  12281. }, files, onError);
  12282. }
  12283. this._internalTexturesCache.push(texture);
  12284. return texture;
  12285. };
  12286. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12287. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12288. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12289. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12290. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12291. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12292. // this.resetTextureCache();
  12293. };
  12294. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12295. if (compression === void 0) { compression = null; }
  12296. if (level === void 0) { level = 0; }
  12297. texture._bufferViewArray = data;
  12298. texture.format = format;
  12299. texture.type = type;
  12300. texture.invertY = invertY;
  12301. texture._compression = compression;
  12302. var gl = this._gl;
  12303. var textureType = this._getWebGLTextureType(type);
  12304. var internalFormat = this._getInternalFormat(format);
  12305. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12306. var needConversion = false;
  12307. if (internalFormat === gl.RGB) {
  12308. internalFormat = gl.RGBA;
  12309. needConversion = true;
  12310. }
  12311. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12312. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12313. if (texture.width % 4 !== 0) {
  12314. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12315. }
  12316. // Data are known to be in +X +Y +Z -X -Y -Z
  12317. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12318. var faceData = data[faceIndex];
  12319. if (compression) {
  12320. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12321. }
  12322. else {
  12323. if (needConversion) {
  12324. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12325. }
  12326. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12327. }
  12328. }
  12329. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12330. if (isPot && texture.generateMipMaps && level === 0) {
  12331. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12332. }
  12333. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12334. // this.resetTextureCache();
  12335. texture.isReady = true;
  12336. };
  12337. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12338. if (compression === void 0) { compression = null; }
  12339. var gl = this._gl;
  12340. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12341. texture.isCube = true;
  12342. texture.generateMipMaps = generateMipMaps;
  12343. texture.format = format;
  12344. texture.type = type;
  12345. if (!this._doNotHandleContextLost) {
  12346. texture._bufferViewArray = data;
  12347. }
  12348. var textureType = this._getWebGLTextureType(type);
  12349. var internalFormat = this._getInternalFormat(format);
  12350. if (internalFormat === gl.RGB) {
  12351. internalFormat = gl.RGBA;
  12352. }
  12353. var width = size;
  12354. var height = width;
  12355. texture.width = width;
  12356. texture.height = height;
  12357. // Double check on POT to generate Mips.
  12358. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12359. if (!isPot) {
  12360. generateMipMaps = false;
  12361. }
  12362. // Upload data if needed. The texture won't be ready until then.
  12363. if (data) {
  12364. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12365. }
  12366. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12367. // Filters
  12368. if (data && generateMipMaps) {
  12369. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12370. }
  12371. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12372. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12373. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12374. }
  12375. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12376. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12377. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12378. }
  12379. else {
  12380. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12381. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12382. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12383. }
  12384. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12385. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12386. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12387. return texture;
  12388. };
  12389. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12390. var _this = this;
  12391. if (onLoad === void 0) { onLoad = null; }
  12392. if (onError === void 0) { onError = null; }
  12393. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12394. if (invertY === void 0) { invertY = false; }
  12395. var gl = this._gl;
  12396. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12397. scene._addPendingData(texture);
  12398. texture.url = url;
  12399. this._internalTexturesCache.push(texture);
  12400. var onerror = function (request, exception) {
  12401. scene._removePendingData(texture);
  12402. if (onError && request) {
  12403. onError(request.status + " " + request.statusText, exception);
  12404. }
  12405. };
  12406. var internalCallback = function (data) {
  12407. var width = texture.width;
  12408. var faceDataArrays = callback(data);
  12409. if (!faceDataArrays) {
  12410. return;
  12411. }
  12412. if (mipmmapGenerator) {
  12413. var textureType = _this._getWebGLTextureType(type);
  12414. var internalFormat = _this._getInternalFormat(format);
  12415. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12416. var needConversion = false;
  12417. if (internalFormat === gl.RGB) {
  12418. internalFormat = gl.RGBA;
  12419. needConversion = true;
  12420. }
  12421. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12422. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12423. var mipData = mipmmapGenerator(faceDataArrays);
  12424. for (var level = 0; level < mipData.length; level++) {
  12425. var mipSize = width >> level;
  12426. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12427. var mipFaceData = mipData[level][faceIndex];
  12428. if (needConversion) {
  12429. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12430. }
  12431. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12432. }
  12433. }
  12434. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12435. }
  12436. else {
  12437. texture.generateMipMaps = !noMipmap;
  12438. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12439. }
  12440. texture.isReady = true;
  12441. // this.resetTextureCache();
  12442. scene._removePendingData(texture);
  12443. if (onLoad) {
  12444. onLoad();
  12445. }
  12446. };
  12447. this._loadFile(url, function (data) {
  12448. internalCallback(data);
  12449. }, undefined, scene.database, true, onerror);
  12450. return texture;
  12451. };
  12452. ;
  12453. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  12454. if (compression === void 0) { compression = null; }
  12455. var internalFormat = this._getInternalFormat(format);
  12456. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12457. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12458. if (!this._doNotHandleContextLost) {
  12459. texture._bufferView = data;
  12460. texture.format = format;
  12461. texture.invertY = invertY;
  12462. texture._compression = compression;
  12463. }
  12464. if (texture.width % 4 !== 0) {
  12465. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12466. }
  12467. if (compression && data) {
  12468. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  12469. }
  12470. else {
  12471. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  12472. }
  12473. if (texture.generateMipMaps) {
  12474. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12475. }
  12476. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12477. // this.resetTextureCache();
  12478. texture.isReady = true;
  12479. };
  12480. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  12481. if (compression === void 0) { compression = null; }
  12482. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  12483. texture.baseWidth = width;
  12484. texture.baseHeight = height;
  12485. texture.baseDepth = depth;
  12486. texture.width = width;
  12487. texture.height = height;
  12488. texture.depth = depth;
  12489. texture.format = format;
  12490. texture.generateMipMaps = generateMipMaps;
  12491. texture.samplingMode = samplingMode;
  12492. texture.is3D = true;
  12493. if (!this._doNotHandleContextLost) {
  12494. texture._bufferView = data;
  12495. }
  12496. this.updateRawTexture3D(texture, data, format, invertY, compression);
  12497. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12498. // Filters
  12499. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12500. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12501. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12502. if (generateMipMaps) {
  12503. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12504. }
  12505. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12506. this._internalTexturesCache.push(texture);
  12507. return texture;
  12508. };
  12509. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  12510. var gl = this._gl;
  12511. if (!gl) {
  12512. return;
  12513. }
  12514. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  12515. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12516. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12517. if (!noMipmap && !isCompressed) {
  12518. gl.generateMipmap(gl.TEXTURE_2D);
  12519. }
  12520. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12521. // this.resetTextureCache();
  12522. if (scene) {
  12523. scene._removePendingData(texture);
  12524. }
  12525. texture.onLoadedObservable.notifyObservers(texture);
  12526. texture.onLoadedObservable.clear();
  12527. };
  12528. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  12529. var _this = this;
  12530. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12531. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  12532. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  12533. var gl = this._gl;
  12534. if (!gl) {
  12535. return;
  12536. }
  12537. if (!texture._webGLTexture) {
  12538. // this.resetTextureCache();
  12539. if (scene) {
  12540. scene._removePendingData(texture);
  12541. }
  12542. return;
  12543. }
  12544. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12545. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12546. texture.baseWidth = width;
  12547. texture.baseHeight = height;
  12548. texture.width = potWidth;
  12549. texture.height = potHeight;
  12550. texture.isReady = true;
  12551. if (processFunction(potWidth, potHeight, function () {
  12552. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12553. })) {
  12554. // Returning as texture needs extra async steps
  12555. return;
  12556. }
  12557. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12558. };
  12559. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  12560. // Create new RGBA data container.
  12561. var rgbaData;
  12562. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  12563. rgbaData = new Float32Array(width * height * 4);
  12564. }
  12565. else {
  12566. rgbaData = new Uint32Array(width * height * 4);
  12567. }
  12568. // Convert each pixel.
  12569. for (var x = 0; x < width; x++) {
  12570. for (var y = 0; y < height; y++) {
  12571. var index = (y * width + x) * 3;
  12572. var newIndex = (y * width + x) * 4;
  12573. // Map Old Value to new value.
  12574. rgbaData[newIndex + 0] = rgbData[index + 0];
  12575. rgbaData[newIndex + 1] = rgbData[index + 1];
  12576. rgbaData[newIndex + 2] = rgbData[index + 2];
  12577. // Add fully opaque alpha channel.
  12578. rgbaData[newIndex + 3] = 1;
  12579. }
  12580. }
  12581. return rgbaData;
  12582. };
  12583. Engine.prototype._releaseFramebufferObjects = function (texture) {
  12584. var gl = this._gl;
  12585. if (texture._framebuffer) {
  12586. gl.deleteFramebuffer(texture._framebuffer);
  12587. texture._framebuffer = null;
  12588. }
  12589. if (texture._depthStencilBuffer) {
  12590. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12591. texture._depthStencilBuffer = null;
  12592. }
  12593. if (texture._MSAAFramebuffer) {
  12594. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12595. texture._MSAAFramebuffer = null;
  12596. }
  12597. if (texture._MSAARenderBuffer) {
  12598. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12599. texture._MSAARenderBuffer = null;
  12600. }
  12601. };
  12602. Engine.prototype._releaseTexture = function (texture) {
  12603. var gl = this._gl;
  12604. this._releaseFramebufferObjects(texture);
  12605. gl.deleteTexture(texture._webGLTexture);
  12606. // Unbind channels
  12607. this.unbindAllTextures();
  12608. var index = this._internalTexturesCache.indexOf(texture);
  12609. if (index !== -1) {
  12610. this._internalTexturesCache.splice(index, 1);
  12611. }
  12612. // Integrated fixed lod samplers.
  12613. if (texture._lodTextureHigh) {
  12614. texture._lodTextureHigh.dispose();
  12615. }
  12616. if (texture._lodTextureMid) {
  12617. texture._lodTextureMid.dispose();
  12618. }
  12619. if (texture._lodTextureLow) {
  12620. texture._lodTextureLow.dispose();
  12621. }
  12622. };
  12623. Engine.prototype.setProgram = function (program) {
  12624. if (this._currentProgram !== program) {
  12625. this._gl.useProgram(program);
  12626. this._currentProgram = program;
  12627. }
  12628. };
  12629. Engine.prototype.bindSamplers = function (effect) {
  12630. this.setProgram(effect.getProgram());
  12631. var samplers = effect.getSamplers();
  12632. for (var index = 0; index < samplers.length; index++) {
  12633. var uniform = effect.getUniform(samplers[index]);
  12634. if (uniform) {
  12635. this._boundUniforms[index] = uniform;
  12636. }
  12637. }
  12638. this._currentEffect = null;
  12639. };
  12640. Engine.prototype._activateTextureChannel = function (channel) {
  12641. if (this._activeChannel !== channel && channel > -1) {
  12642. this._gl.activeTexture(this._gl.TEXTURE0 + channel);
  12643. this._activeChannel = channel;
  12644. }
  12645. };
  12646. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  12647. var index = this._boundTexturesStack.indexOf(internalTexture);
  12648. if (index > -1 && index !== this._boundTexturesStack.length - 1) {
  12649. this._boundTexturesStack.splice(index, 1);
  12650. this._boundTexturesStack.push(internalTexture);
  12651. }
  12652. };
  12653. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  12654. var currentSlot = internalTexture._designatedSlot;
  12655. internalTexture._designatedSlot = -1;
  12656. var index = this._boundTexturesStack.indexOf(internalTexture);
  12657. if (index > -1) {
  12658. this._boundTexturesStack.splice(index, 1);
  12659. if (currentSlot > -1) {
  12660. this._boundTexturesCache[currentSlot] = null;
  12661. this._nextFreeTextureSlots.push(currentSlot);
  12662. }
  12663. }
  12664. return currentSlot;
  12665. };
  12666. Engine.prototype._bindTextureDirectly = function (target, texture, doNotBindUniformToTextureChannel) {
  12667. if (doNotBindUniformToTextureChannel === void 0) { doNotBindUniformToTextureChannel = false; }
  12668. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  12669. var isTextureForRendering = texture && texture._initialSlot > -1;
  12670. if (currentTextureBound !== texture) {
  12671. if (currentTextureBound && !this.disableTextureBindingOptimization) {
  12672. this._removeDesignatedSlot(currentTextureBound);
  12673. }
  12674. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  12675. if (this._activeChannel >= 0) {
  12676. this._boundTexturesCache[this._activeChannel] = texture;
  12677. if (isTextureForRendering && !this.disableTextureBindingOptimization) {
  12678. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  12679. if (slotIndex > -1) {
  12680. this._nextFreeTextureSlots.splice(slotIndex, 1);
  12681. }
  12682. this._boundTexturesStack.push(texture);
  12683. }
  12684. }
  12685. }
  12686. if (isTextureForRendering && this._activeChannel > -1) {
  12687. texture._designatedSlot = this._activeChannel;
  12688. if (!doNotBindUniformToTextureChannel) {
  12689. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  12690. }
  12691. }
  12692. };
  12693. Engine.prototype._bindTexture = function (channel, texture) {
  12694. if (channel < 0) {
  12695. return;
  12696. }
  12697. if (texture) {
  12698. channel = this._getCorrectTextureChannel(channel, texture);
  12699. }
  12700. this._activateTextureChannel(channel);
  12701. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  12702. };
  12703. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12704. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  12705. };
  12706. Engine.prototype.unbindAllTextures = function () {
  12707. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  12708. this._activateTextureChannel(channel);
  12709. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12710. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12711. if (this.webGLVersion > 1) {
  12712. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12713. }
  12714. }
  12715. };
  12716. Engine.prototype.setTexture = function (channel, uniform, texture) {
  12717. if (channel < 0) {
  12718. return;
  12719. }
  12720. if (uniform) {
  12721. this._boundUniforms[channel] = uniform;
  12722. }
  12723. this._setTexture(channel, texture);
  12724. };
  12725. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  12726. if (!internalTexture) {
  12727. return -1;
  12728. }
  12729. internalTexture._initialSlot = channel;
  12730. if (this.disableTextureBindingOptimization) {
  12731. if (channel !== internalTexture._designatedSlot) {
  12732. this._textureCollisions.addCount(1, false);
  12733. }
  12734. }
  12735. else {
  12736. if (channel !== internalTexture._designatedSlot) {
  12737. if (internalTexture._designatedSlot > -1) {
  12738. return internalTexture._designatedSlot;
  12739. }
  12740. else {
  12741. // No slot for this texture, let's pick a new one (if we find a free slot)
  12742. if (this._nextFreeTextureSlots.length) {
  12743. return this._nextFreeTextureSlots[0];
  12744. }
  12745. // We need to recycle the oldest bound texture, sorry.
  12746. this._textureCollisions.addCount(1, false);
  12747. return this._removeDesignatedSlot(this._boundTexturesStack[0]);
  12748. }
  12749. }
  12750. }
  12751. return channel;
  12752. };
  12753. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  12754. var uniform = this._boundUniforms[sourceSlot];
  12755. this._gl.uniform1i(uniform, destination);
  12756. };
  12757. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  12758. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  12759. // Not ready?
  12760. if (!texture) {
  12761. if (this._boundTexturesCache[channel] != null) {
  12762. this._activateTextureChannel(channel);
  12763. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12764. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12765. if (this.webGLVersion > 1) {
  12766. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12767. }
  12768. }
  12769. return false;
  12770. }
  12771. // Video
  12772. var alreadyActivated = false;
  12773. if (texture.video) {
  12774. this._activateTextureChannel(channel);
  12775. alreadyActivated = true;
  12776. texture.update();
  12777. }
  12778. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  12779. texture.delayLoad();
  12780. return false;
  12781. }
  12782. var internalTexture;
  12783. if (texture.isReady()) {
  12784. internalTexture = texture.getInternalTexture();
  12785. }
  12786. else if (texture.isCube) {
  12787. internalTexture = this.emptyCubeTexture;
  12788. }
  12789. else if (texture.is3D) {
  12790. internalTexture = this.emptyTexture3D;
  12791. }
  12792. else {
  12793. internalTexture = this.emptyTexture;
  12794. }
  12795. if (!isPartOfTextureArray) {
  12796. channel = this._getCorrectTextureChannel(channel, internalTexture);
  12797. }
  12798. if (this._boundTexturesCache[channel] === internalTexture) {
  12799. this._moveBoundTextureOnTop(internalTexture);
  12800. if (!isPartOfTextureArray) {
  12801. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  12802. }
  12803. return false;
  12804. }
  12805. if (!alreadyActivated) {
  12806. this._activateTextureChannel(channel);
  12807. }
  12808. if (internalTexture && internalTexture.is3D) {
  12809. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  12810. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12811. internalTexture._cachedWrapU = texture.wrapU;
  12812. switch (texture.wrapU) {
  12813. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12814. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12815. break;
  12816. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12817. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12818. break;
  12819. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12820. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12821. break;
  12822. }
  12823. }
  12824. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12825. internalTexture._cachedWrapV = texture.wrapV;
  12826. switch (texture.wrapV) {
  12827. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12828. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12829. break;
  12830. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12831. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12832. break;
  12833. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12834. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12835. break;
  12836. }
  12837. }
  12838. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  12839. internalTexture._cachedWrapR = texture.wrapR;
  12840. switch (texture.wrapV) {
  12841. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12842. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  12843. break;
  12844. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12845. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  12846. break;
  12847. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12848. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  12849. break;
  12850. }
  12851. }
  12852. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  12853. }
  12854. else if (internalTexture && internalTexture.isCube) {
  12855. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  12856. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  12857. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  12858. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  12859. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  12860. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  12861. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  12862. }
  12863. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  12864. }
  12865. else {
  12866. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  12867. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12868. internalTexture._cachedWrapU = texture.wrapU;
  12869. switch (texture.wrapU) {
  12870. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12871. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12872. break;
  12873. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12874. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12875. break;
  12876. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12877. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12878. break;
  12879. }
  12880. }
  12881. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12882. internalTexture._cachedWrapV = texture.wrapV;
  12883. switch (texture.wrapV) {
  12884. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12885. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12886. break;
  12887. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12888. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12889. break;
  12890. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12891. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12892. break;
  12893. }
  12894. }
  12895. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  12896. }
  12897. return true;
  12898. };
  12899. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  12900. if (channel < 0 || !uniform) {
  12901. return;
  12902. }
  12903. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  12904. this._textureUnits = new Int32Array(textures.length);
  12905. }
  12906. for (var i = 0; i < textures.length; i++) {
  12907. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  12908. }
  12909. this._gl.uniform1iv(uniform, this._textureUnits);
  12910. for (var index = 0; index < textures.length; index++) {
  12911. this._setTexture(this._textureUnits[index], textures[index], true);
  12912. }
  12913. };
  12914. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  12915. var internalTexture = texture.getInternalTexture();
  12916. if (!internalTexture) {
  12917. return;
  12918. }
  12919. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  12920. var value = texture.anisotropicFilteringLevel;
  12921. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  12922. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  12923. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  12924. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  12925. }
  12926. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  12927. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  12928. internalTexture._cachedAnisotropicFilteringLevel = value;
  12929. }
  12930. };
  12931. Engine.prototype.readPixels = function (x, y, width, height) {
  12932. var data = new Uint8Array(height * width * 4);
  12933. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  12934. return data;
  12935. };
  12936. /**
  12937. * Add an externaly attached data from its key.
  12938. * This method call will fail and return false, if such key already exists.
  12939. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  12940. * @param key the unique key that identifies the data
  12941. * @param data the data object to associate to the key for this Engine instance
  12942. * @return true if no such key were already present and the data was added successfully, false otherwise
  12943. */
  12944. Engine.prototype.addExternalData = function (key, data) {
  12945. if (!this._externalData) {
  12946. this._externalData = new BABYLON.StringDictionary();
  12947. }
  12948. return this._externalData.add(key, data);
  12949. };
  12950. /**
  12951. * Get an externaly attached data from its key
  12952. * @param key the unique key that identifies the data
  12953. * @return the associated data, if present (can be null), or undefined if not present
  12954. */
  12955. Engine.prototype.getExternalData = function (key) {
  12956. if (!this._externalData) {
  12957. this._externalData = new BABYLON.StringDictionary();
  12958. }
  12959. return this._externalData.get(key);
  12960. };
  12961. /**
  12962. * Get an externaly attached data from its key, create it using a factory if it's not already present
  12963. * @param key the unique key that identifies the data
  12964. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  12965. * @return the associated data, can be null if the factory returned null.
  12966. */
  12967. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  12968. if (!this._externalData) {
  12969. this._externalData = new BABYLON.StringDictionary();
  12970. }
  12971. return this._externalData.getOrAddWithFactory(key, factory);
  12972. };
  12973. /**
  12974. * Remove an externaly attached data from the Engine instance
  12975. * @param key the unique key that identifies the data
  12976. * @return true if the data was successfully removed, false if it doesn't exist
  12977. */
  12978. Engine.prototype.removeExternalData = function (key) {
  12979. if (!this._externalData) {
  12980. this._externalData = new BABYLON.StringDictionary();
  12981. }
  12982. return this._externalData.remove(key);
  12983. };
  12984. Engine.prototype.unbindAllAttributes = function () {
  12985. if (this._mustWipeVertexAttributes) {
  12986. this._mustWipeVertexAttributes = false;
  12987. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12988. this._gl.disableVertexAttribArray(i);
  12989. this._vertexAttribArraysEnabled[i] = false;
  12990. this._currentBufferPointers[i].active = false;
  12991. }
  12992. return;
  12993. }
  12994. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  12995. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  12996. continue;
  12997. }
  12998. this._gl.disableVertexAttribArray(i);
  12999. this._vertexAttribArraysEnabled[i] = false;
  13000. this._currentBufferPointers[i].active = false;
  13001. }
  13002. };
  13003. Engine.prototype.releaseEffects = function () {
  13004. for (var name in this._compiledEffects) {
  13005. this._deleteProgram(this._compiledEffects[name]._program);
  13006. }
  13007. this._compiledEffects = {};
  13008. };
  13009. // Dispose
  13010. Engine.prototype.dispose = function () {
  13011. this.hideLoadingUI();
  13012. this.stopRenderLoop();
  13013. // Release postProcesses
  13014. while (this.postProcesses.length) {
  13015. this.postProcesses[0].dispose();
  13016. }
  13017. // Empty texture
  13018. if (this._emptyTexture) {
  13019. this._releaseTexture(this._emptyTexture);
  13020. this._emptyTexture = null;
  13021. }
  13022. if (this._emptyCubeTexture) {
  13023. this._releaseTexture(this._emptyCubeTexture);
  13024. this._emptyCubeTexture = null;
  13025. }
  13026. // Rescale PP
  13027. if (this._rescalePostProcess) {
  13028. this._rescalePostProcess.dispose();
  13029. }
  13030. // Release scenes
  13031. while (this.scenes.length) {
  13032. this.scenes[0].dispose();
  13033. }
  13034. // Release audio engine
  13035. if (Engine.audioEngine) {
  13036. Engine.audioEngine.dispose();
  13037. }
  13038. // Release effects
  13039. this.releaseEffects();
  13040. // Unbind
  13041. this.unbindAllAttributes();
  13042. if (this._dummyFramebuffer) {
  13043. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13044. }
  13045. //WebVR
  13046. this.disableVR();
  13047. // Events
  13048. if (BABYLON.Tools.IsWindowObjectExist()) {
  13049. window.removeEventListener("blur", this._onBlur);
  13050. window.removeEventListener("focus", this._onFocus);
  13051. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13052. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13053. if (this._renderingCanvas) {
  13054. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13055. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13056. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13057. if (!this._doNotHandleContextLost) {
  13058. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13059. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13060. }
  13061. }
  13062. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13063. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13064. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13065. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13066. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13067. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13068. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13069. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13070. if (this._onVrDisplayConnect) {
  13071. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13072. if (this._onVrDisplayDisconnect) {
  13073. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13074. }
  13075. if (this._onVrDisplayPresentChange) {
  13076. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13077. }
  13078. this._onVrDisplayConnect = null;
  13079. this._onVrDisplayDisconnect = null;
  13080. }
  13081. }
  13082. // Remove from Instances
  13083. var index = Engine.Instances.indexOf(this);
  13084. if (index >= 0) {
  13085. Engine.Instances.splice(index, 1);
  13086. }
  13087. this._workingCanvas = null;
  13088. this._workingContext = null;
  13089. this._currentBufferPointers = [];
  13090. this._renderingCanvas = null;
  13091. this._currentProgram = null;
  13092. this.onResizeObservable.clear();
  13093. this.onCanvasBlurObservable.clear();
  13094. this.onCanvasFocusObservable.clear();
  13095. this.onCanvasPointerOutObservable.clear();
  13096. this.onBeginFrameObservable.clear();
  13097. this.onEndFrameObservable.clear();
  13098. BABYLON.Effect.ResetCache();
  13099. // Abort active requests
  13100. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13101. var request = _a[_i];
  13102. request.abort();
  13103. }
  13104. };
  13105. // Loading screen
  13106. Engine.prototype.displayLoadingUI = function () {
  13107. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13108. return;
  13109. }
  13110. var loadingScreen = this.loadingScreen;
  13111. if (loadingScreen) {
  13112. loadingScreen.displayLoadingUI();
  13113. }
  13114. };
  13115. Engine.prototype.hideLoadingUI = function () {
  13116. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13117. return;
  13118. }
  13119. var loadingScreen = this.loadingScreen;
  13120. if (loadingScreen) {
  13121. loadingScreen.hideLoadingUI();
  13122. }
  13123. };
  13124. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13125. get: function () {
  13126. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13127. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13128. return this._loadingScreen;
  13129. },
  13130. set: function (loadingScreen) {
  13131. this._loadingScreen = loadingScreen;
  13132. },
  13133. enumerable: true,
  13134. configurable: true
  13135. });
  13136. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13137. set: function (text) {
  13138. this.loadingScreen.loadingUIText = text;
  13139. },
  13140. enumerable: true,
  13141. configurable: true
  13142. });
  13143. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13144. set: function (color) {
  13145. this.loadingScreen.loadingUIBackgroundColor = color;
  13146. },
  13147. enumerable: true,
  13148. configurable: true
  13149. });
  13150. Engine.prototype.attachContextLostEvent = function (callback) {
  13151. if (this._renderingCanvas) {
  13152. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13153. }
  13154. };
  13155. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13156. if (this._renderingCanvas) {
  13157. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13158. }
  13159. };
  13160. Engine.prototype.getVertexShaderSource = function (program) {
  13161. var shaders = this._gl.getAttachedShaders(program);
  13162. if (!shaders) {
  13163. return null;
  13164. }
  13165. return this._gl.getShaderSource(shaders[0]);
  13166. };
  13167. Engine.prototype.getFragmentShaderSource = function (program) {
  13168. var shaders = this._gl.getAttachedShaders(program);
  13169. if (!shaders) {
  13170. return null;
  13171. }
  13172. return this._gl.getShaderSource(shaders[1]);
  13173. };
  13174. Engine.prototype.getError = function () {
  13175. return this._gl.getError();
  13176. };
  13177. // FPS
  13178. Engine.prototype.getFps = function () {
  13179. return this._fps;
  13180. };
  13181. Engine.prototype.getDeltaTime = function () {
  13182. return this._deltaTime;
  13183. };
  13184. Engine.prototype._measureFps = function () {
  13185. this._performanceMonitor.sampleFrame();
  13186. this._fps = this._performanceMonitor.averageFPS;
  13187. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13188. };
  13189. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13190. if (faceIndex === void 0) { faceIndex = -1; }
  13191. var gl = this._gl;
  13192. if (!this._dummyFramebuffer) {
  13193. var dummy = gl.createFramebuffer();
  13194. if (!dummy) {
  13195. throw new Error("Unable to create dummy framebuffer");
  13196. }
  13197. this._dummyFramebuffer = dummy;
  13198. }
  13199. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13200. if (faceIndex > -1) {
  13201. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13202. }
  13203. else {
  13204. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13205. }
  13206. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13207. var buffer;
  13208. switch (readType) {
  13209. case gl.UNSIGNED_BYTE:
  13210. buffer = new Uint8Array(4 * width * height);
  13211. readType = gl.UNSIGNED_BYTE;
  13212. break;
  13213. default:
  13214. buffer = new Float32Array(4 * width * height);
  13215. readType = gl.FLOAT;
  13216. break;
  13217. }
  13218. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13219. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13220. return buffer;
  13221. };
  13222. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13223. if (this._webGLVersion > 1) {
  13224. return this._caps.colorBufferFloat;
  13225. }
  13226. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13227. };
  13228. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13229. if (this._webGLVersion > 1) {
  13230. return this._caps.colorBufferFloat;
  13231. }
  13232. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13233. };
  13234. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13235. Engine.prototype._canRenderToFramebuffer = function (type) {
  13236. var gl = this._gl;
  13237. //clear existing errors
  13238. while (gl.getError() !== gl.NO_ERROR) { }
  13239. var successful = true;
  13240. var texture = gl.createTexture();
  13241. gl.bindTexture(gl.TEXTURE_2D, texture);
  13242. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13243. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13244. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13245. var fb = gl.createFramebuffer();
  13246. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13247. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13248. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13249. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13250. successful = successful && (gl.getError() === gl.NO_ERROR);
  13251. //try render by clearing frame buffer's color buffer
  13252. if (successful) {
  13253. gl.clear(gl.COLOR_BUFFER_BIT);
  13254. successful = successful && (gl.getError() === gl.NO_ERROR);
  13255. }
  13256. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13257. if (successful) {
  13258. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13259. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13260. var readFormat = gl.RGBA;
  13261. var readType = gl.UNSIGNED_BYTE;
  13262. var buffer = new Uint8Array(4);
  13263. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13264. successful = successful && (gl.getError() === gl.NO_ERROR);
  13265. }
  13266. //clean up
  13267. gl.deleteTexture(texture);
  13268. gl.deleteFramebuffer(fb);
  13269. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13270. //clear accumulated errors
  13271. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13272. return successful;
  13273. };
  13274. Engine.prototype._getWebGLTextureType = function (type) {
  13275. if (type === Engine.TEXTURETYPE_FLOAT) {
  13276. return this._gl.FLOAT;
  13277. }
  13278. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13279. // Add Half Float Constant.
  13280. return this._gl.HALF_FLOAT_OES;
  13281. }
  13282. return this._gl.UNSIGNED_BYTE;
  13283. };
  13284. ;
  13285. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13286. if (this._webGLVersion === 1) {
  13287. return this._gl.RGBA;
  13288. }
  13289. if (type === Engine.TEXTURETYPE_FLOAT) {
  13290. return this._gl.RGBA32F;
  13291. }
  13292. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13293. return this._gl.RGBA16F;
  13294. }
  13295. return this._gl.RGBA;
  13296. };
  13297. ;
  13298. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13299. if (type === Engine.TEXTURETYPE_FLOAT) {
  13300. return this._gl.RGBA32F;
  13301. }
  13302. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13303. return this._gl.RGBA16F;
  13304. }
  13305. return this._gl.RGBA8;
  13306. };
  13307. ;
  13308. Engine.prototype.createQuery = function () {
  13309. return this._gl.createQuery();
  13310. };
  13311. Engine.prototype.deleteQuery = function (query) {
  13312. this._gl.deleteQuery(query);
  13313. return this;
  13314. };
  13315. Engine.prototype.isQueryResultAvailable = function (query) {
  13316. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13317. };
  13318. Engine.prototype.getQueryResult = function (query) {
  13319. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13320. };
  13321. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13322. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13323. this._gl.beginQuery(glAlgorithm, query);
  13324. return this;
  13325. };
  13326. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13327. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13328. this._gl.endQuery(glAlgorithm);
  13329. return this;
  13330. };
  13331. /* Time queries */
  13332. Engine.prototype._createTimeQuery = function () {
  13333. var timerQuery = this._caps.timerQuery;
  13334. if (timerQuery.createQueryEXT) {
  13335. return timerQuery.createQueryEXT();
  13336. }
  13337. return this.createQuery();
  13338. };
  13339. Engine.prototype._deleteTimeQuery = function (query) {
  13340. var timerQuery = this._caps.timerQuery;
  13341. if (timerQuery.deleteQueryEXT) {
  13342. timerQuery.deleteQueryEXT(query);
  13343. return;
  13344. }
  13345. this.deleteQuery(query);
  13346. };
  13347. Engine.prototype._getTimeQueryResult = function (query) {
  13348. var timerQuery = this._caps.timerQuery;
  13349. if (timerQuery.getQueryObjectEXT) {
  13350. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13351. }
  13352. return this.getQueryResult(query);
  13353. };
  13354. Engine.prototype._getTimeQueryAvailability = function (query) {
  13355. var timerQuery = this._caps.timerQuery;
  13356. if (timerQuery.getQueryObjectEXT) {
  13357. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13358. }
  13359. return this.isQueryResultAvailable(query);
  13360. };
  13361. Engine.prototype.startTimeQuery = function () {
  13362. var timerQuery = this._caps.timerQuery;
  13363. if (!timerQuery) {
  13364. return null;
  13365. }
  13366. var token = new BABYLON._TimeToken();
  13367. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13368. if (this._caps.canUseTimestampForTimerQuery) {
  13369. token._startTimeQuery = this._createTimeQuery();
  13370. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13371. }
  13372. else {
  13373. if (this._currentNonTimestampToken) {
  13374. return this._currentNonTimestampToken;
  13375. }
  13376. token._timeElapsedQuery = this._createTimeQuery();
  13377. if (timerQuery.beginQueryEXT) {
  13378. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13379. }
  13380. else {
  13381. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13382. }
  13383. this._currentNonTimestampToken = token;
  13384. }
  13385. return token;
  13386. };
  13387. Engine.prototype.endTimeQuery = function (token) {
  13388. var timerQuery = this._caps.timerQuery;
  13389. if (!timerQuery || !token) {
  13390. return -1;
  13391. }
  13392. if (this._caps.canUseTimestampForTimerQuery) {
  13393. if (!token._startTimeQuery) {
  13394. return -1;
  13395. }
  13396. if (!token._endTimeQuery) {
  13397. token._endTimeQuery = this._createTimeQuery();
  13398. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13399. }
  13400. }
  13401. else if (!token._timeElapsedQueryEnded) {
  13402. if (!token._timeElapsedQuery) {
  13403. return -1;
  13404. }
  13405. if (timerQuery.endQueryEXT) {
  13406. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13407. }
  13408. else {
  13409. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13410. }
  13411. token._timeElapsedQueryEnded = true;
  13412. }
  13413. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13414. var available = false;
  13415. if (token._endTimeQuery) {
  13416. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13417. }
  13418. else if (token._timeElapsedQuery) {
  13419. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13420. }
  13421. if (available && !disjoint) {
  13422. var result = 0;
  13423. if (this._caps.canUseTimestampForTimerQuery) {
  13424. if (!token._startTimeQuery || !token._endTimeQuery) {
  13425. return -1;
  13426. }
  13427. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  13428. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  13429. result = timeEnd - timeStart;
  13430. this._deleteTimeQuery(token._startTimeQuery);
  13431. this._deleteTimeQuery(token._endTimeQuery);
  13432. token._startTimeQuery = null;
  13433. token._endTimeQuery = null;
  13434. }
  13435. else {
  13436. if (!token._timeElapsedQuery) {
  13437. return -1;
  13438. }
  13439. result = this._getTimeQueryResult(token._timeElapsedQuery);
  13440. this._deleteTimeQuery(token._timeElapsedQuery);
  13441. token._timeElapsedQuery = null;
  13442. token._timeElapsedQueryEnded = false;
  13443. this._currentNonTimestampToken = null;
  13444. }
  13445. return result;
  13446. }
  13447. return -1;
  13448. };
  13449. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  13450. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  13451. };
  13452. // Transform feedback
  13453. Engine.prototype.createTransformFeedback = function () {
  13454. return this._gl.createTransformFeedback();
  13455. };
  13456. Engine.prototype.deleteTransformFeedback = function (value) {
  13457. this._gl.deleteTransformFeedback(value);
  13458. };
  13459. Engine.prototype.bindTransformFeedback = function (value) {
  13460. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  13461. };
  13462. Engine.prototype.beginTransformFeedback = function (usePoints) {
  13463. if (usePoints === void 0) { usePoints = true; }
  13464. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  13465. };
  13466. Engine.prototype.endTransformFeedback = function () {
  13467. this._gl.endTransformFeedback();
  13468. };
  13469. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  13470. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  13471. };
  13472. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  13473. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  13474. };
  13475. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  13476. var _this = this;
  13477. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  13478. this._activeRequests.push(request);
  13479. request.onCompleteObservable.add(function (request) {
  13480. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  13481. });
  13482. return request;
  13483. };
  13484. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  13485. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  13486. var onload = function (data) {
  13487. loadedFiles[index] = data;
  13488. loadedFiles._internalCount++;
  13489. if (loadedFiles._internalCount === 6) {
  13490. onfinish(loadedFiles);
  13491. }
  13492. };
  13493. var onerror = function (request, exception) {
  13494. if (onErrorCallBack && request) {
  13495. onErrorCallBack(request.status + " " + request.statusText, exception);
  13496. }
  13497. };
  13498. this._loadFile(url, onload, undefined, undefined, true, onerror);
  13499. };
  13500. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  13501. if (onError === void 0) { onError = null; }
  13502. var loadedFiles = [];
  13503. loadedFiles._internalCount = 0;
  13504. for (var index = 0; index < 6; index++) {
  13505. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  13506. }
  13507. };
  13508. // Statics
  13509. Engine.isSupported = function () {
  13510. try {
  13511. var tempcanvas = document.createElement("canvas");
  13512. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  13513. return gl != null && !!window.WebGLRenderingContext;
  13514. }
  13515. catch (e) {
  13516. return false;
  13517. }
  13518. };
  13519. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  13520. Engine.ExceptionList = [
  13521. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  13522. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  13523. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  13524. ];
  13525. Engine.Instances = new Array();
  13526. // Const statics
  13527. Engine._ALPHA_DISABLE = 0;
  13528. Engine._ALPHA_ADD = 1;
  13529. Engine._ALPHA_COMBINE = 2;
  13530. Engine._ALPHA_SUBTRACT = 3;
  13531. Engine._ALPHA_MULTIPLY = 4;
  13532. Engine._ALPHA_MAXIMIZED = 5;
  13533. Engine._ALPHA_ONEONE = 6;
  13534. Engine._ALPHA_PREMULTIPLIED = 7;
  13535. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  13536. Engine._ALPHA_INTERPOLATE = 9;
  13537. Engine._ALPHA_SCREENMODE = 10;
  13538. Engine._DELAYLOADSTATE_NONE = 0;
  13539. Engine._DELAYLOADSTATE_LOADED = 1;
  13540. Engine._DELAYLOADSTATE_LOADING = 2;
  13541. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  13542. Engine._TEXTUREFORMAT_ALPHA = 0;
  13543. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  13544. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  13545. Engine._TEXTUREFORMAT_RGB = 4;
  13546. Engine._TEXTUREFORMAT_RGBA = 5;
  13547. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  13548. Engine._TEXTURETYPE_FLOAT = 1;
  13549. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  13550. // Depht or Stencil test Constants.
  13551. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  13552. 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.
  13553. 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.
  13554. 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.
  13555. 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.
  13556. 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.
  13557. 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.
  13558. 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.
  13559. // Stencil Actions Constants.
  13560. Engine._KEEP = 0x1E00;
  13561. Engine._REPLACE = 0x1E01;
  13562. Engine._INCR = 0x1E02;
  13563. Engine._DECR = 0x1E03;
  13564. Engine._INVERT = 0x150A;
  13565. Engine._INCR_WRAP = 0x8507;
  13566. Engine._DECR_WRAP = 0x8508;
  13567. // Texture rescaling mode
  13568. Engine._SCALEMODE_FLOOR = 1;
  13569. Engine._SCALEMODE_NEAREST = 2;
  13570. Engine._SCALEMODE_CEILING = 3;
  13571. // Updatable statics so stick with vars here
  13572. Engine.CollisionsEpsilon = 0.001;
  13573. Engine.CodeRepository = "src/";
  13574. Engine.ShadersRepository = "src/Shaders/";
  13575. return Engine;
  13576. }());
  13577. BABYLON.Engine = Engine;
  13578. })(BABYLON || (BABYLON = {}));
  13579. //# sourceMappingURL=babylon.engine.js.map
  13580. var BABYLON;
  13581. (function (BABYLON) {
  13582. /**
  13583. * Node is the basic class for all scene objects (Mesh, Light Camera).
  13584. */
  13585. var Node = /** @class */ (function () {
  13586. /**
  13587. * @constructor
  13588. * @param {string} name - the name and id to be given to this node
  13589. * @param {BABYLON.Scene} the scene this node will be added to
  13590. */
  13591. function Node(name, scene) {
  13592. if (scene === void 0) { scene = null; }
  13593. this.state = "";
  13594. this.metadata = null;
  13595. this.doNotSerialize = false;
  13596. this.animations = new Array();
  13597. this._ranges = {};
  13598. this._isEnabled = true;
  13599. this._isReady = true;
  13600. this._currentRenderId = -1;
  13601. this._parentRenderId = -1;
  13602. /**
  13603. * An event triggered when the mesh is disposed.
  13604. * @type {BABYLON.Observable}
  13605. */
  13606. this.onDisposeObservable = new BABYLON.Observable();
  13607. // Behaviors
  13608. this._behaviors = new Array();
  13609. this.name = name;
  13610. this.id = name;
  13611. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  13612. this.uniqueId = this._scene.getUniqueId();
  13613. this._initCache();
  13614. }
  13615. Object.defineProperty(Node.prototype, "parent", {
  13616. get: function () {
  13617. return this._parentNode;
  13618. },
  13619. set: function (parent) {
  13620. if (this._parentNode === parent) {
  13621. return;
  13622. }
  13623. // Remove self from list of children of parent
  13624. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  13625. var index = this._parentNode._children.indexOf(this);
  13626. if (index !== -1) {
  13627. this._parentNode._children.splice(index, 1);
  13628. }
  13629. }
  13630. // Store new parent
  13631. this._parentNode = parent;
  13632. // Add as child to new parent
  13633. if (this._parentNode) {
  13634. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  13635. this._parentNode._children = new Array();
  13636. }
  13637. this._parentNode._children.push(this);
  13638. }
  13639. },
  13640. enumerable: true,
  13641. configurable: true
  13642. });
  13643. Node.prototype.getClassName = function () {
  13644. return "Node";
  13645. };
  13646. Object.defineProperty(Node.prototype, "onDispose", {
  13647. set: function (callback) {
  13648. if (this._onDisposeObserver) {
  13649. this.onDisposeObservable.remove(this._onDisposeObserver);
  13650. }
  13651. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  13652. },
  13653. enumerable: true,
  13654. configurable: true
  13655. });
  13656. Node.prototype.getScene = function () {
  13657. return this._scene;
  13658. };
  13659. Node.prototype.getEngine = function () {
  13660. return this._scene.getEngine();
  13661. };
  13662. Node.prototype.addBehavior = function (behavior) {
  13663. var _this = this;
  13664. var index = this._behaviors.indexOf(behavior);
  13665. if (index !== -1) {
  13666. return this;
  13667. }
  13668. behavior.init();
  13669. if (this._scene.isLoading) {
  13670. // We defer the attach when the scene will be loaded
  13671. var observer = this._scene.onDataLoadedObservable.add(function () {
  13672. behavior.attach(_this);
  13673. setTimeout(function () {
  13674. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  13675. _this._scene.onDataLoadedObservable.remove(observer);
  13676. }, 0);
  13677. });
  13678. }
  13679. else {
  13680. behavior.attach(this);
  13681. }
  13682. this._behaviors.push(behavior);
  13683. return this;
  13684. };
  13685. Node.prototype.removeBehavior = function (behavior) {
  13686. var index = this._behaviors.indexOf(behavior);
  13687. if (index === -1) {
  13688. return this;
  13689. }
  13690. this._behaviors[index].detach();
  13691. this._behaviors.splice(index, 1);
  13692. return this;
  13693. };
  13694. Object.defineProperty(Node.prototype, "behaviors", {
  13695. get: function () {
  13696. return this._behaviors;
  13697. },
  13698. enumerable: true,
  13699. configurable: true
  13700. });
  13701. Node.prototype.getBehaviorByName = function (name) {
  13702. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13703. var behavior = _a[_i];
  13704. if (behavior.name === name) {
  13705. return behavior;
  13706. }
  13707. }
  13708. return null;
  13709. };
  13710. // override it in derived class
  13711. Node.prototype.getWorldMatrix = function () {
  13712. return BABYLON.Matrix.Identity();
  13713. };
  13714. // override it in derived class if you add new variables to the cache
  13715. // and call the parent class method
  13716. Node.prototype._initCache = function () {
  13717. this._cache = {};
  13718. this._cache.parent = undefined;
  13719. };
  13720. Node.prototype.updateCache = function (force) {
  13721. if (!force && this.isSynchronized())
  13722. return;
  13723. this._cache.parent = this.parent;
  13724. this._updateCache();
  13725. };
  13726. // override it in derived class if you add new variables to the cache
  13727. // and call the parent class method if !ignoreParentClass
  13728. Node.prototype._updateCache = function (ignoreParentClass) {
  13729. };
  13730. // override it in derived class if you add new variables to the cache
  13731. Node.prototype._isSynchronized = function () {
  13732. return true;
  13733. };
  13734. Node.prototype._markSyncedWithParent = function () {
  13735. if (this.parent) {
  13736. this._parentRenderId = this.parent._currentRenderId;
  13737. }
  13738. };
  13739. Node.prototype.isSynchronizedWithParent = function () {
  13740. if (!this.parent) {
  13741. return true;
  13742. }
  13743. if (this._parentRenderId !== this.parent._currentRenderId) {
  13744. return false;
  13745. }
  13746. return this.parent.isSynchronized();
  13747. };
  13748. Node.prototype.isSynchronized = function (updateCache) {
  13749. var check = this.hasNewParent();
  13750. check = check || !this.isSynchronizedWithParent();
  13751. check = check || !this._isSynchronized();
  13752. if (updateCache)
  13753. this.updateCache(true);
  13754. return !check;
  13755. };
  13756. Node.prototype.hasNewParent = function (update) {
  13757. if (this._cache.parent === this.parent)
  13758. return false;
  13759. if (update)
  13760. this._cache.parent = this.parent;
  13761. return true;
  13762. };
  13763. /**
  13764. * Is this node ready to be used/rendered
  13765. * @return {boolean} is it ready
  13766. */
  13767. Node.prototype.isReady = function () {
  13768. return this._isReady;
  13769. };
  13770. /**
  13771. * Is this node enabled.
  13772. * 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.
  13773. * @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.
  13774. * @return {boolean} whether this node (and its parent) is enabled.
  13775. * @see setEnabled
  13776. */
  13777. Node.prototype.isEnabled = function (checkAncestors) {
  13778. if (checkAncestors === void 0) { checkAncestors = true; }
  13779. if (checkAncestors === false) {
  13780. return this._isEnabled;
  13781. }
  13782. if (this._isEnabled === false) {
  13783. return false;
  13784. }
  13785. if (this.parent !== undefined && this.parent !== null) {
  13786. return this.parent.isEnabled(checkAncestors);
  13787. }
  13788. return true;
  13789. };
  13790. /**
  13791. * Set the enabled state of this node.
  13792. * @param {boolean} value - the new enabled state
  13793. * @see isEnabled
  13794. */
  13795. Node.prototype.setEnabled = function (value) {
  13796. this._isEnabled = value;
  13797. };
  13798. /**
  13799. * Is this node a descendant of the given node.
  13800. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  13801. * @param {BABYLON.Node} ancestor - The parent node to inspect
  13802. * @see parent
  13803. */
  13804. Node.prototype.isDescendantOf = function (ancestor) {
  13805. if (this.parent) {
  13806. if (this.parent === ancestor) {
  13807. return true;
  13808. }
  13809. return this.parent.isDescendantOf(ancestor);
  13810. }
  13811. return false;
  13812. };
  13813. /**
  13814. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  13815. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  13816. * @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.
  13817. * @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.
  13818. */
  13819. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  13820. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  13821. if (!this._children) {
  13822. return;
  13823. }
  13824. for (var index = 0; index < this._children.length; index++) {
  13825. var item = this._children[index];
  13826. if (!predicate || predicate(item)) {
  13827. results.push(item);
  13828. }
  13829. if (!directDescendantsOnly) {
  13830. item._getDescendants(results, false, predicate);
  13831. }
  13832. }
  13833. };
  13834. /**
  13835. * Will return all nodes that have this node as ascendant.
  13836. * @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.
  13837. * @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.
  13838. * @return {BABYLON.Node[]} all children nodes of all types.
  13839. */
  13840. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  13841. var results = new Array();
  13842. this._getDescendants(results, directDescendantsOnly, predicate);
  13843. return results;
  13844. };
  13845. /**
  13846. * Get all child-meshes of this node.
  13847. */
  13848. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  13849. var results = [];
  13850. this._getDescendants(results, directDescendantsOnly, function (node) {
  13851. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  13852. });
  13853. return results;
  13854. };
  13855. /**
  13856. * Get all child-transformNodes of this node.
  13857. */
  13858. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  13859. var results = [];
  13860. this._getDescendants(results, directDescendantsOnly, function (node) {
  13861. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  13862. });
  13863. return results;
  13864. };
  13865. /**
  13866. * Get all direct children of this node.
  13867. */
  13868. Node.prototype.getChildren = function (predicate) {
  13869. return this.getDescendants(true, predicate);
  13870. };
  13871. Node.prototype._setReady = function (state) {
  13872. if (state === this._isReady) {
  13873. return;
  13874. }
  13875. if (!state) {
  13876. this._isReady = false;
  13877. return;
  13878. }
  13879. this._isReady = true;
  13880. if (this.onReady) {
  13881. this.onReady(this);
  13882. }
  13883. };
  13884. Node.prototype.getAnimationByName = function (name) {
  13885. for (var i = 0; i < this.animations.length; i++) {
  13886. var animation = this.animations[i];
  13887. if (animation.name === name) {
  13888. return animation;
  13889. }
  13890. }
  13891. return null;
  13892. };
  13893. Node.prototype.createAnimationRange = function (name, from, to) {
  13894. // check name not already in use
  13895. if (!this._ranges[name]) {
  13896. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  13897. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13898. if (this.animations[i]) {
  13899. this.animations[i].createRange(name, from, to);
  13900. }
  13901. }
  13902. }
  13903. };
  13904. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  13905. if (deleteFrames === void 0) { deleteFrames = true; }
  13906. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13907. if (this.animations[i]) {
  13908. this.animations[i].deleteRange(name, deleteFrames);
  13909. }
  13910. }
  13911. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  13912. };
  13913. Node.prototype.getAnimationRange = function (name) {
  13914. return this._ranges[name];
  13915. };
  13916. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  13917. var range = this.getAnimationRange(name);
  13918. if (!range) {
  13919. return;
  13920. }
  13921. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  13922. };
  13923. Node.prototype.serializeAnimationRanges = function () {
  13924. var serializationRanges = [];
  13925. for (var name in this._ranges) {
  13926. var localRange = this._ranges[name];
  13927. if (!localRange) {
  13928. continue;
  13929. }
  13930. var range = {};
  13931. range.name = name;
  13932. range.from = localRange.from;
  13933. range.to = localRange.to;
  13934. serializationRanges.push(range);
  13935. }
  13936. return serializationRanges;
  13937. };
  13938. // override it in derived class
  13939. Node.prototype.computeWorldMatrix = function (force) {
  13940. return BABYLON.Matrix.Identity();
  13941. };
  13942. Node.prototype.dispose = function () {
  13943. this.parent = null;
  13944. // Callback
  13945. this.onDisposeObservable.notifyObservers(this);
  13946. this.onDisposeObservable.clear();
  13947. // Behaviors
  13948. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13949. var behavior = _a[_i];
  13950. behavior.detach();
  13951. }
  13952. this._behaviors = [];
  13953. };
  13954. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  13955. if (parsedNode.ranges) {
  13956. for (var index = 0; index < parsedNode.ranges.length; index++) {
  13957. var data = parsedNode.ranges[index];
  13958. node.createAnimationRange(data.name, data.from, data.to);
  13959. }
  13960. }
  13961. };
  13962. __decorate([
  13963. BABYLON.serialize()
  13964. ], Node.prototype, "name", void 0);
  13965. __decorate([
  13966. BABYLON.serialize()
  13967. ], Node.prototype, "id", void 0);
  13968. __decorate([
  13969. BABYLON.serialize()
  13970. ], Node.prototype, "uniqueId", void 0);
  13971. __decorate([
  13972. BABYLON.serialize()
  13973. ], Node.prototype, "state", void 0);
  13974. __decorate([
  13975. BABYLON.serialize()
  13976. ], Node.prototype, "metadata", void 0);
  13977. return Node;
  13978. }());
  13979. BABYLON.Node = Node;
  13980. })(BABYLON || (BABYLON = {}));
  13981. //# sourceMappingURL=babylon.node.js.map
  13982. var BABYLON;
  13983. (function (BABYLON) {
  13984. var BoundingSphere = /** @class */ (function () {
  13985. function BoundingSphere(minimum, maximum) {
  13986. this.minimum = minimum;
  13987. this.maximum = maximum;
  13988. this._tempRadiusVector = BABYLON.Vector3.Zero();
  13989. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  13990. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  13991. this.radius = distance * 0.5;
  13992. this.centerWorld = BABYLON.Vector3.Zero();
  13993. this._update(BABYLON.Matrix.Identity());
  13994. }
  13995. // Methods
  13996. BoundingSphere.prototype._update = function (world) {
  13997. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  13998. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  13999. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14000. };
  14001. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14002. for (var i = 0; i < 6; i++) {
  14003. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14004. return false;
  14005. }
  14006. return true;
  14007. };
  14008. BoundingSphere.prototype.intersectsPoint = function (point) {
  14009. var x = this.centerWorld.x - point.x;
  14010. var y = this.centerWorld.y - point.y;
  14011. var z = this.centerWorld.z - point.z;
  14012. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14013. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14014. return false;
  14015. return true;
  14016. };
  14017. // Statics
  14018. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14019. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14020. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14021. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14022. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14023. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14024. return false;
  14025. return true;
  14026. };
  14027. return BoundingSphere;
  14028. }());
  14029. BABYLON.BoundingSphere = BoundingSphere;
  14030. })(BABYLON || (BABYLON = {}));
  14031. //# sourceMappingURL=babylon.boundingSphere.js.map
  14032. var BABYLON;
  14033. (function (BABYLON) {
  14034. var BoundingBox = /** @class */ (function () {
  14035. function BoundingBox(minimum, maximum) {
  14036. this.minimum = minimum;
  14037. this.maximum = maximum;
  14038. this.vectors = new Array();
  14039. this.vectorsWorld = new Array();
  14040. // Bounding vectors
  14041. this.vectors.push(this.minimum.clone());
  14042. this.vectors.push(this.maximum.clone());
  14043. this.vectors.push(this.minimum.clone());
  14044. this.vectors[2].x = this.maximum.x;
  14045. this.vectors.push(this.minimum.clone());
  14046. this.vectors[3].y = this.maximum.y;
  14047. this.vectors.push(this.minimum.clone());
  14048. this.vectors[4].z = this.maximum.z;
  14049. this.vectors.push(this.maximum.clone());
  14050. this.vectors[5].z = this.minimum.z;
  14051. this.vectors.push(this.maximum.clone());
  14052. this.vectors[6].x = this.minimum.x;
  14053. this.vectors.push(this.maximum.clone());
  14054. this.vectors[7].y = this.minimum.y;
  14055. // OBB
  14056. this.center = this.maximum.add(this.minimum).scale(0.5);
  14057. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14058. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14059. // World
  14060. for (var index = 0; index < this.vectors.length; index++) {
  14061. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14062. }
  14063. this.minimumWorld = BABYLON.Vector3.Zero();
  14064. this.maximumWorld = BABYLON.Vector3.Zero();
  14065. this.centerWorld = BABYLON.Vector3.Zero();
  14066. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14067. this._update(BABYLON.Matrix.Identity());
  14068. }
  14069. // Methods
  14070. BoundingBox.prototype.getWorldMatrix = function () {
  14071. return this._worldMatrix;
  14072. };
  14073. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14074. this._worldMatrix.copyFrom(matrix);
  14075. return this;
  14076. };
  14077. BoundingBox.prototype._update = function (world) {
  14078. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14079. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14080. for (var index = 0; index < this.vectors.length; index++) {
  14081. var v = this.vectorsWorld[index];
  14082. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14083. if (v.x < this.minimumWorld.x)
  14084. this.minimumWorld.x = v.x;
  14085. if (v.y < this.minimumWorld.y)
  14086. this.minimumWorld.y = v.y;
  14087. if (v.z < this.minimumWorld.z)
  14088. this.minimumWorld.z = v.z;
  14089. if (v.x > this.maximumWorld.x)
  14090. this.maximumWorld.x = v.x;
  14091. if (v.y > this.maximumWorld.y)
  14092. this.maximumWorld.y = v.y;
  14093. if (v.z > this.maximumWorld.z)
  14094. this.maximumWorld.z = v.z;
  14095. }
  14096. // Extend
  14097. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14098. this.extendSizeWorld.scaleInPlace(0.5);
  14099. // OBB
  14100. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14101. this.centerWorld.scaleInPlace(0.5);
  14102. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14103. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14104. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14105. this._worldMatrix = world;
  14106. };
  14107. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14108. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14109. };
  14110. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14111. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14112. };
  14113. BoundingBox.prototype.intersectsPoint = function (point) {
  14114. var delta = -BABYLON.Epsilon;
  14115. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14116. return false;
  14117. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14118. return false;
  14119. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14120. return false;
  14121. return true;
  14122. };
  14123. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14124. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14125. };
  14126. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14127. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14128. return false;
  14129. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14130. return false;
  14131. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14132. return false;
  14133. return true;
  14134. };
  14135. // Statics
  14136. BoundingBox.Intersects = function (box0, box1) {
  14137. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14138. return false;
  14139. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14140. return false;
  14141. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14142. return false;
  14143. return true;
  14144. };
  14145. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14146. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14147. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14148. return (num <= (sphereRadius * sphereRadius));
  14149. };
  14150. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14151. for (var p = 0; p < 6; p++) {
  14152. for (var i = 0; i < 8; i++) {
  14153. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14154. return false;
  14155. }
  14156. }
  14157. }
  14158. return true;
  14159. };
  14160. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14161. for (var p = 0; p < 6; p++) {
  14162. var inCount = 8;
  14163. for (var i = 0; i < 8; i++) {
  14164. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14165. --inCount;
  14166. }
  14167. else {
  14168. break;
  14169. }
  14170. }
  14171. if (inCount === 0)
  14172. return false;
  14173. }
  14174. return true;
  14175. };
  14176. return BoundingBox;
  14177. }());
  14178. BABYLON.BoundingBox = BoundingBox;
  14179. })(BABYLON || (BABYLON = {}));
  14180. //# sourceMappingURL=babylon.boundingBox.js.map
  14181. var BABYLON;
  14182. (function (BABYLON) {
  14183. var computeBoxExtents = function (axis, box) {
  14184. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14185. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14186. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14187. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14188. var r = r0 + r1 + r2;
  14189. return {
  14190. min: p - r,
  14191. max: p + r
  14192. };
  14193. };
  14194. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14195. var axisOverlap = function (axis, box0, box1) {
  14196. var result0 = computeBoxExtents(axis, box0);
  14197. var result1 = computeBoxExtents(axis, box1);
  14198. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14199. };
  14200. var BoundingInfo = /** @class */ (function () {
  14201. function BoundingInfo(minimum, maximum) {
  14202. this.minimum = minimum;
  14203. this.maximum = maximum;
  14204. this._isLocked = false;
  14205. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14206. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14207. }
  14208. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14209. get: function () {
  14210. return this._isLocked;
  14211. },
  14212. set: function (value) {
  14213. this._isLocked = value;
  14214. },
  14215. enumerable: true,
  14216. configurable: true
  14217. });
  14218. // Methods
  14219. BoundingInfo.prototype.update = function (world) {
  14220. if (this._isLocked) {
  14221. return;
  14222. }
  14223. this.boundingBox._update(world);
  14224. this.boundingSphere._update(world);
  14225. };
  14226. /**
  14227. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14228. * @param center New center of the bounding info
  14229. * @param extend New extend of the bounding info
  14230. */
  14231. BoundingInfo.prototype.centerOn = function (center, extend) {
  14232. this.minimum = center.subtract(extend);
  14233. this.maximum = center.add(extend);
  14234. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14235. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14236. return this;
  14237. };
  14238. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14239. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14240. return false;
  14241. return this.boundingBox.isInFrustum(frustumPlanes);
  14242. };
  14243. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14244. /**
  14245. * Gets the world distance between the min and max points of the bounding box
  14246. */
  14247. get: function () {
  14248. var boundingBox = this.boundingBox;
  14249. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14250. return size.length();
  14251. },
  14252. enumerable: true,
  14253. configurable: true
  14254. });
  14255. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14256. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14257. };
  14258. BoundingInfo.prototype._checkCollision = function (collider) {
  14259. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14260. };
  14261. BoundingInfo.prototype.intersectsPoint = function (point) {
  14262. if (!this.boundingSphere.centerWorld) {
  14263. return false;
  14264. }
  14265. if (!this.boundingSphere.intersectsPoint(point)) {
  14266. return false;
  14267. }
  14268. if (!this.boundingBox.intersectsPoint(point)) {
  14269. return false;
  14270. }
  14271. return true;
  14272. };
  14273. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14274. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14275. return false;
  14276. }
  14277. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14278. return false;
  14279. }
  14280. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14281. return false;
  14282. }
  14283. if (!precise) {
  14284. return true;
  14285. }
  14286. var box0 = this.boundingBox;
  14287. var box1 = boundingInfo.boundingBox;
  14288. if (!axisOverlap(box0.directions[0], box0, box1))
  14289. return false;
  14290. if (!axisOverlap(box0.directions[1], box0, box1))
  14291. return false;
  14292. if (!axisOverlap(box0.directions[2], box0, box1))
  14293. return false;
  14294. if (!axisOverlap(box1.directions[0], box0, box1))
  14295. return false;
  14296. if (!axisOverlap(box1.directions[1], box0, box1))
  14297. return false;
  14298. if (!axisOverlap(box1.directions[2], box0, box1))
  14299. return false;
  14300. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14301. return false;
  14302. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14303. return false;
  14304. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14305. return false;
  14306. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14307. return false;
  14308. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14309. return false;
  14310. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14311. return false;
  14312. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14313. return false;
  14314. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14315. return false;
  14316. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14317. return false;
  14318. return true;
  14319. };
  14320. return BoundingInfo;
  14321. }());
  14322. BABYLON.BoundingInfo = BoundingInfo;
  14323. })(BABYLON || (BABYLON = {}));
  14324. //# sourceMappingURL=babylon.boundingInfo.js.map
  14325. var BABYLON;
  14326. (function (BABYLON) {
  14327. var TransformNode = /** @class */ (function (_super) {
  14328. __extends(TransformNode, _super);
  14329. function TransformNode(name, scene, isPure) {
  14330. if (scene === void 0) { scene = null; }
  14331. if (isPure === void 0) { isPure = true; }
  14332. var _this = _super.call(this, name, scene) || this;
  14333. // Properties
  14334. _this._rotation = BABYLON.Vector3.Zero();
  14335. _this._scaling = BABYLON.Vector3.One();
  14336. _this._isDirty = false;
  14337. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14338. _this.scalingDeterminant = 1;
  14339. _this.infiniteDistance = false;
  14340. _this.position = BABYLON.Vector3.Zero();
  14341. _this._localWorld = BABYLON.Matrix.Zero();
  14342. _this._worldMatrix = BABYLON.Matrix.Zero();
  14343. _this._worldMatrixDeterminant = 0;
  14344. _this._absolutePosition = BABYLON.Vector3.Zero();
  14345. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14346. _this._postMultiplyPivotMatrix = false;
  14347. _this._isWorldMatrixFrozen = false;
  14348. /**
  14349. * An event triggered after the world matrix is updated
  14350. * @type {BABYLON.Observable}
  14351. */
  14352. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14353. _this._nonUniformScaling = false;
  14354. if (isPure) {
  14355. _this.getScene().addTransformNode(_this);
  14356. }
  14357. return _this;
  14358. }
  14359. Object.defineProperty(TransformNode.prototype, "rotation", {
  14360. /**
  14361. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14362. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14363. * Default : (0.0, 0.0, 0.0)
  14364. */
  14365. get: function () {
  14366. return this._rotation;
  14367. },
  14368. set: function (newRotation) {
  14369. this._rotation = newRotation;
  14370. },
  14371. enumerable: true,
  14372. configurable: true
  14373. });
  14374. Object.defineProperty(TransformNode.prototype, "scaling", {
  14375. /**
  14376. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14377. * Default : (1.0, 1.0, 1.0)
  14378. */
  14379. get: function () {
  14380. return this._scaling;
  14381. },
  14382. /**
  14383. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14384. * Default : (1.0, 1.0, 1.0)
  14385. */
  14386. set: function (newScaling) {
  14387. this._scaling = newScaling;
  14388. },
  14389. enumerable: true,
  14390. configurable: true
  14391. });
  14392. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14393. /**
  14394. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14395. * It's null by default.
  14396. * 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)
  14397. */
  14398. get: function () {
  14399. return this._rotationQuaternion;
  14400. },
  14401. set: function (quaternion) {
  14402. this._rotationQuaternion = quaternion;
  14403. //reset the rotation vector.
  14404. if (quaternion && this.rotation.length()) {
  14405. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14406. }
  14407. },
  14408. enumerable: true,
  14409. configurable: true
  14410. });
  14411. /**
  14412. * Returns the latest update of the World matrix
  14413. * Returns a Matrix.
  14414. */
  14415. TransformNode.prototype.getWorldMatrix = function () {
  14416. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14417. this.computeWorldMatrix();
  14418. }
  14419. return this._worldMatrix;
  14420. };
  14421. /**
  14422. * Returns the latest update of the World matrix determinant.
  14423. */
  14424. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  14425. return this._worldMatrixDeterminant;
  14426. };
  14427. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14428. /**
  14429. * Returns directly the latest state of the mesh World matrix.
  14430. * A Matrix is returned.
  14431. */
  14432. get: function () {
  14433. return this._worldMatrix;
  14434. },
  14435. enumerable: true,
  14436. configurable: true
  14437. });
  14438. /**
  14439. * Copies the paramater passed Matrix into the mesh Pose matrix.
  14440. * Returns the AbstractMesh.
  14441. */
  14442. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  14443. this._poseMatrix.copyFrom(matrix);
  14444. return this;
  14445. };
  14446. /**
  14447. * Returns the mesh Pose matrix.
  14448. * Returned object : Matrix
  14449. */
  14450. TransformNode.prototype.getPoseMatrix = function () {
  14451. return this._poseMatrix;
  14452. };
  14453. TransformNode.prototype._isSynchronized = function () {
  14454. if (this._isDirty) {
  14455. return false;
  14456. }
  14457. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  14458. return false;
  14459. if (this._cache.pivotMatrixUpdated) {
  14460. return false;
  14461. }
  14462. if (this.infiniteDistance) {
  14463. return false;
  14464. }
  14465. if (!this._cache.position.equals(this.position))
  14466. return false;
  14467. if (this.rotationQuaternion) {
  14468. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14469. return false;
  14470. }
  14471. if (!this._cache.rotation.equals(this.rotation))
  14472. return false;
  14473. if (!this._cache.scaling.equals(this.scaling))
  14474. return false;
  14475. return true;
  14476. };
  14477. TransformNode.prototype._initCache = function () {
  14478. _super.prototype._initCache.call(this);
  14479. this._cache.localMatrixUpdated = false;
  14480. this._cache.position = BABYLON.Vector3.Zero();
  14481. this._cache.scaling = BABYLON.Vector3.Zero();
  14482. this._cache.rotation = BABYLON.Vector3.Zero();
  14483. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14484. this._cache.billboardMode = -1;
  14485. };
  14486. TransformNode.prototype.markAsDirty = function (property) {
  14487. if (property === "rotation") {
  14488. this.rotationQuaternion = null;
  14489. }
  14490. this._currentRenderId = Number.MAX_VALUE;
  14491. this._isDirty = true;
  14492. return this;
  14493. };
  14494. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  14495. /**
  14496. * Returns the current mesh absolute position.
  14497. * Retuns a Vector3.
  14498. */
  14499. get: function () {
  14500. return this._absolutePosition;
  14501. },
  14502. enumerable: true,
  14503. configurable: true
  14504. });
  14505. /**
  14506. * Sets a new pivot matrix to the mesh.
  14507. * Returns the AbstractMesh.
  14508. */
  14509. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14510. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14511. this._pivotMatrix = matrix.clone();
  14512. this._cache.pivotMatrixUpdated = true;
  14513. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14514. if (this._postMultiplyPivotMatrix) {
  14515. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14516. }
  14517. return this;
  14518. };
  14519. /**
  14520. * Returns the mesh pivot matrix.
  14521. * Default : Identity.
  14522. * A Matrix is returned.
  14523. */
  14524. TransformNode.prototype.getPivotMatrix = function () {
  14525. return this._pivotMatrix;
  14526. };
  14527. /**
  14528. * Prevents the World matrix to be computed any longer.
  14529. * Returns the AbstractMesh.
  14530. */
  14531. TransformNode.prototype.freezeWorldMatrix = function () {
  14532. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  14533. this.computeWorldMatrix(true);
  14534. this._isWorldMatrixFrozen = true;
  14535. return this;
  14536. };
  14537. /**
  14538. * Allows back the World matrix computation.
  14539. * Returns the AbstractMesh.
  14540. */
  14541. TransformNode.prototype.unfreezeWorldMatrix = function () {
  14542. this._isWorldMatrixFrozen = false;
  14543. this.computeWorldMatrix(true);
  14544. return this;
  14545. };
  14546. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  14547. /**
  14548. * True if the World matrix has been frozen.
  14549. * Returns a boolean.
  14550. */
  14551. get: function () {
  14552. return this._isWorldMatrixFrozen;
  14553. },
  14554. enumerable: true,
  14555. configurable: true
  14556. });
  14557. /**
  14558. * Retuns the mesh absolute position in the World.
  14559. * Returns a Vector3.
  14560. */
  14561. TransformNode.prototype.getAbsolutePosition = function () {
  14562. this.computeWorldMatrix();
  14563. return this._absolutePosition;
  14564. };
  14565. /**
  14566. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  14567. * Returns the AbstractMesh.
  14568. */
  14569. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  14570. if (!absolutePosition) {
  14571. return this;
  14572. }
  14573. var absolutePositionX;
  14574. var absolutePositionY;
  14575. var absolutePositionZ;
  14576. if (absolutePosition.x === undefined) {
  14577. if (arguments.length < 3) {
  14578. return this;
  14579. }
  14580. absolutePositionX = arguments[0];
  14581. absolutePositionY = arguments[1];
  14582. absolutePositionZ = arguments[2];
  14583. }
  14584. else {
  14585. absolutePositionX = absolutePosition.x;
  14586. absolutePositionY = absolutePosition.y;
  14587. absolutePositionZ = absolutePosition.z;
  14588. }
  14589. if (this.parent) {
  14590. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14591. invertParentWorldMatrix.invert();
  14592. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14593. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14594. }
  14595. else {
  14596. this.position.x = absolutePositionX;
  14597. this.position.y = absolutePositionY;
  14598. this.position.z = absolutePositionZ;
  14599. }
  14600. return this;
  14601. };
  14602. /**
  14603. * Sets the mesh position in its local space.
  14604. * Returns the AbstractMesh.
  14605. */
  14606. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  14607. this.computeWorldMatrix();
  14608. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14609. return this;
  14610. };
  14611. /**
  14612. * Returns the mesh position in the local space from the current World matrix values.
  14613. * Returns a new Vector3.
  14614. */
  14615. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  14616. this.computeWorldMatrix();
  14617. var invLocalWorldMatrix = this._localWorld.clone();
  14618. invLocalWorldMatrix.invert();
  14619. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14620. };
  14621. /**
  14622. * Translates the mesh along the passed Vector3 in its local space.
  14623. * Returns the AbstractMesh.
  14624. */
  14625. TransformNode.prototype.locallyTranslate = function (vector3) {
  14626. this.computeWorldMatrix(true);
  14627. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14628. return this;
  14629. };
  14630. /**
  14631. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  14632. * @param targetPoint the position (must be in same space as current mesh) to look at
  14633. * @param yawCor optional yaw (y-axis) correction in radians
  14634. * @param pitchCor optional pitch (x-axis) correction in radians
  14635. * @param rollCor optional roll (z-axis) correction in radians
  14636. * @param space the choosen space of the target
  14637. * @returns the TransformNode.
  14638. */
  14639. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14640. if (yawCor === void 0) { yawCor = 0; }
  14641. if (pitchCor === void 0) { pitchCor = 0; }
  14642. if (rollCor === void 0) { rollCor = 0; }
  14643. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14644. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  14645. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14646. targetPoint.subtractToRef(pos, dv);
  14647. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14648. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14649. var pitch = Math.atan2(dv.y, len);
  14650. if (this.rotationQuaternion) {
  14651. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14652. }
  14653. else {
  14654. this.rotation.x = pitch + pitchCor;
  14655. this.rotation.y = yaw + yawCor;
  14656. this.rotation.z = rollCor;
  14657. }
  14658. return this;
  14659. };
  14660. /**
  14661. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14662. * This Vector3 is expressed in the World space.
  14663. */
  14664. TransformNode.prototype.getDirection = function (localAxis) {
  14665. var result = BABYLON.Vector3.Zero();
  14666. this.getDirectionToRef(localAxis, result);
  14667. return result;
  14668. };
  14669. /**
  14670. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14671. * localAxis is expressed in the mesh local space.
  14672. * result is computed in the Wordl space from the mesh World matrix.
  14673. * Returns the AbstractMesh.
  14674. */
  14675. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  14676. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14677. return this;
  14678. };
  14679. TransformNode.prototype.setPivotPoint = function (point, space) {
  14680. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14681. if (this.getScene().getRenderId() == 0) {
  14682. this.computeWorldMatrix(true);
  14683. }
  14684. var wm = this.getWorldMatrix();
  14685. if (space == BABYLON.Space.WORLD) {
  14686. var tmat = BABYLON.Tmp.Matrix[0];
  14687. wm.invertToRef(tmat);
  14688. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14689. }
  14690. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14691. this._pivotMatrix.m[12] = -point.x;
  14692. this._pivotMatrix.m[13] = -point.y;
  14693. this._pivotMatrix.m[14] = -point.z;
  14694. this._cache.pivotMatrixUpdated = true;
  14695. return this;
  14696. };
  14697. /**
  14698. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14699. */
  14700. TransformNode.prototype.getPivotPoint = function () {
  14701. var point = BABYLON.Vector3.Zero();
  14702. this.getPivotPointToRef(point);
  14703. return point;
  14704. };
  14705. /**
  14706. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14707. * Returns the AbstractMesh.
  14708. */
  14709. TransformNode.prototype.getPivotPointToRef = function (result) {
  14710. result.x = -this._pivotMatrix.m[12];
  14711. result.y = -this._pivotMatrix.m[13];
  14712. result.z = -this._pivotMatrix.m[14];
  14713. return this;
  14714. };
  14715. /**
  14716. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14717. */
  14718. TransformNode.prototype.getAbsolutePivotPoint = function () {
  14719. var point = BABYLON.Vector3.Zero();
  14720. this.getAbsolutePivotPointToRef(point);
  14721. return point;
  14722. };
  14723. /**
  14724. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14725. * Returns the AbstractMesh.
  14726. */
  14727. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  14728. result.x = this._pivotMatrix.m[12];
  14729. result.y = this._pivotMatrix.m[13];
  14730. result.z = this._pivotMatrix.m[14];
  14731. this.getPivotPointToRef(result);
  14732. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14733. return this;
  14734. };
  14735. /**
  14736. * Defines the passed node as the parent of the current node.
  14737. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  14738. * Returns the TransformNode.
  14739. */
  14740. TransformNode.prototype.setParent = function (node) {
  14741. if (node === null) {
  14742. var rotation = BABYLON.Tmp.Quaternion[0];
  14743. var position = BABYLON.Tmp.Vector3[0];
  14744. var scale = BABYLON.Tmp.Vector3[1];
  14745. if (this.parent && this.parent.computeWorldMatrix) {
  14746. this.parent.computeWorldMatrix(true);
  14747. }
  14748. this.computeWorldMatrix(true);
  14749. this.getWorldMatrix().decompose(scale, rotation, position);
  14750. if (this.rotationQuaternion) {
  14751. this.rotationQuaternion.copyFrom(rotation);
  14752. }
  14753. else {
  14754. rotation.toEulerAnglesToRef(this.rotation);
  14755. }
  14756. this.scaling.x = scale.x;
  14757. this.scaling.y = scale.y;
  14758. this.scaling.z = scale.z;
  14759. this.position.x = position.x;
  14760. this.position.y = position.y;
  14761. this.position.z = position.z;
  14762. }
  14763. else {
  14764. var rotation = BABYLON.Tmp.Quaternion[0];
  14765. var position = BABYLON.Tmp.Vector3[0];
  14766. var scale = BABYLON.Tmp.Vector3[1];
  14767. var diffMatrix = BABYLON.Tmp.Matrix[0];
  14768. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  14769. this.computeWorldMatrix(true);
  14770. node.computeWorldMatrix(true);
  14771. node.getWorldMatrix().invertToRef(invParentMatrix);
  14772. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  14773. diffMatrix.decompose(scale, rotation, position);
  14774. if (this.rotationQuaternion) {
  14775. this.rotationQuaternion.copyFrom(rotation);
  14776. }
  14777. else {
  14778. rotation.toEulerAnglesToRef(this.rotation);
  14779. }
  14780. this.position.x = position.x;
  14781. this.position.y = position.y;
  14782. this.position.z = position.z;
  14783. this.scaling.x = scale.x;
  14784. this.scaling.y = scale.y;
  14785. this.scaling.z = scale.z;
  14786. }
  14787. this.parent = node;
  14788. return this;
  14789. };
  14790. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  14791. get: function () {
  14792. return this._nonUniformScaling;
  14793. },
  14794. enumerable: true,
  14795. configurable: true
  14796. });
  14797. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  14798. if (this._nonUniformScaling === value) {
  14799. return false;
  14800. }
  14801. this._nonUniformScaling = true;
  14802. return true;
  14803. };
  14804. /**
  14805. * Attach the current TransformNode to another TransformNode associated with a bone
  14806. * @param bone Bone affecting the TransformNode
  14807. * @param affectedTransformNode TransformNode associated with the bone
  14808. */
  14809. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  14810. this._transformToBoneReferal = affectedTransformNode;
  14811. this.parent = bone;
  14812. if (bone.getWorldMatrix().determinant() < 0) {
  14813. this.scalingDeterminant *= -1;
  14814. }
  14815. return this;
  14816. };
  14817. TransformNode.prototype.detachFromBone = function () {
  14818. if (!this.parent) {
  14819. return this;
  14820. }
  14821. if (this.parent.getWorldMatrix().determinant() < 0) {
  14822. this.scalingDeterminant *= -1;
  14823. }
  14824. this._transformToBoneReferal = null;
  14825. this.parent = null;
  14826. return this;
  14827. };
  14828. /**
  14829. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  14830. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14831. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14832. * The passed axis is also normalized.
  14833. * Returns the AbstractMesh.
  14834. */
  14835. TransformNode.prototype.rotate = function (axis, amount, space) {
  14836. axis.normalize();
  14837. if (!this.rotationQuaternion) {
  14838. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14839. this.rotation = BABYLON.Vector3.Zero();
  14840. }
  14841. var rotationQuaternion;
  14842. if (!space || space === BABYLON.Space.LOCAL) {
  14843. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14844. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  14845. }
  14846. else {
  14847. if (this.parent) {
  14848. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14849. invertParentWorldMatrix.invert();
  14850. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  14851. }
  14852. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14853. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14854. }
  14855. return this;
  14856. };
  14857. /**
  14858. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  14859. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14860. * The passed axis is also normalized.
  14861. * Returns the AbstractMesh.
  14862. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  14863. */
  14864. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  14865. axis.normalize();
  14866. if (!this.rotationQuaternion) {
  14867. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14868. this.rotation.copyFromFloats(0, 0, 0);
  14869. }
  14870. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  14871. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  14872. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  14873. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  14874. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  14875. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  14876. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  14877. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  14878. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14879. return this;
  14880. };
  14881. /**
  14882. * Translates the mesh along the axis vector for the passed distance in the given space.
  14883. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14884. * Returns the AbstractMesh.
  14885. */
  14886. TransformNode.prototype.translate = function (axis, distance, space) {
  14887. var displacementVector = axis.scale(distance);
  14888. if (!space || space === BABYLON.Space.LOCAL) {
  14889. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  14890. this.setPositionWithLocalVector(tempV3);
  14891. }
  14892. else {
  14893. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  14894. }
  14895. return this;
  14896. };
  14897. /**
  14898. * Adds a rotation step to the mesh current rotation.
  14899. * x, y, z are Euler angles expressed in radians.
  14900. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  14901. * This means this rotation is made in the mesh local space only.
  14902. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  14903. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  14904. * ```javascript
  14905. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  14906. * ```
  14907. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  14908. * 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.
  14909. * Returns the AbstractMesh.
  14910. */
  14911. TransformNode.prototype.addRotation = function (x, y, z) {
  14912. var rotationQuaternion;
  14913. if (this.rotationQuaternion) {
  14914. rotationQuaternion = this.rotationQuaternion;
  14915. }
  14916. else {
  14917. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  14918. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  14919. }
  14920. var accumulation = BABYLON.Tmp.Quaternion[0];
  14921. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  14922. rotationQuaternion.multiplyInPlace(accumulation);
  14923. if (!this.rotationQuaternion) {
  14924. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  14925. }
  14926. return this;
  14927. };
  14928. /**
  14929. * Computes the mesh World matrix and returns it.
  14930. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14931. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14932. * If the parameter `force`is set to `true`, the actual computation is done.
  14933. * Returns the mesh World Matrix.
  14934. */
  14935. TransformNode.prototype.computeWorldMatrix = function (force) {
  14936. if (this._isWorldMatrixFrozen) {
  14937. return this._worldMatrix;
  14938. }
  14939. if (!force && this.isSynchronized(true)) {
  14940. return this._worldMatrix;
  14941. }
  14942. this._cache.position.copyFrom(this.position);
  14943. this._cache.scaling.copyFrom(this.scaling);
  14944. this._cache.pivotMatrixUpdated = false;
  14945. this._cache.billboardMode = this.billboardMode;
  14946. this._currentRenderId = this.getScene().getRenderId();
  14947. this._isDirty = false;
  14948. // Scaling
  14949. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14950. // Rotation
  14951. //rotate, if quaternion is set and rotation was used
  14952. if (this.rotationQuaternion) {
  14953. var len = this.rotation.length();
  14954. if (len) {
  14955. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14956. this.rotation.copyFromFloats(0, 0, 0);
  14957. }
  14958. }
  14959. if (this.rotationQuaternion) {
  14960. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14961. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14962. }
  14963. else {
  14964. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14965. this._cache.rotation.copyFrom(this.rotation);
  14966. }
  14967. // Translation
  14968. var camera = this.getScene().activeCamera;
  14969. if (this.infiniteDistance && !this.parent && camera) {
  14970. var cameraWorldMatrix = camera.getWorldMatrix();
  14971. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14972. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14973. }
  14974. else {
  14975. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14976. }
  14977. // Composing transformations
  14978. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14979. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14980. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14981. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14982. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  14983. // Need to decompose each rotation here
  14984. var currentPosition = BABYLON.Tmp.Vector3[3];
  14985. if (this.parent && this.parent.getWorldMatrix) {
  14986. if (this._transformToBoneReferal) {
  14987. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14988. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14989. }
  14990. else {
  14991. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14992. }
  14993. }
  14994. else {
  14995. currentPosition.copyFrom(this.position);
  14996. }
  14997. currentPosition.subtractInPlace(camera.globalPosition);
  14998. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14999. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15000. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15001. }
  15002. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15003. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15004. }
  15005. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15006. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15007. }
  15008. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15009. }
  15010. else {
  15011. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15012. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15013. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15014. }
  15015. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15016. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15017. }
  15018. // Local world
  15019. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15020. // Parent
  15021. if (this.parent && this.parent.getWorldMatrix) {
  15022. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15023. if (this._transformToBoneReferal) {
  15024. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15025. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15026. }
  15027. else {
  15028. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15029. }
  15030. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15031. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15032. this._worldMatrix.copyFrom(this._localWorld);
  15033. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15034. }
  15035. else {
  15036. if (this._transformToBoneReferal) {
  15037. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15038. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15039. }
  15040. else {
  15041. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15042. }
  15043. }
  15044. this._markSyncedWithParent();
  15045. }
  15046. else {
  15047. this._worldMatrix.copyFrom(this._localWorld);
  15048. }
  15049. // Post multiply inverse of pivotMatrix
  15050. if (this._postMultiplyPivotMatrix) {
  15051. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15052. }
  15053. // Normal matrix
  15054. if (this.scaling.isNonUniform) {
  15055. this._updateNonUniformScalingState(true);
  15056. }
  15057. else if (this.parent && this.parent._nonUniformScaling) {
  15058. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15059. }
  15060. else {
  15061. this._updateNonUniformScalingState(false);
  15062. }
  15063. this._afterComputeWorldMatrix();
  15064. // Absolute position
  15065. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15066. // Callbacks
  15067. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15068. if (!this._poseMatrix) {
  15069. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15070. }
  15071. // Cache the determinant
  15072. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15073. return this._worldMatrix;
  15074. };
  15075. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15076. };
  15077. /**
  15078. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15079. * @param func: callback function to add
  15080. *
  15081. * Returns the TransformNode.
  15082. */
  15083. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15084. this.onAfterWorldMatrixUpdateObservable.add(func);
  15085. return this;
  15086. };
  15087. /**
  15088. * Removes a registered callback function.
  15089. * Returns the TransformNode.
  15090. */
  15091. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15092. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15093. return this;
  15094. };
  15095. /**
  15096. * Clone the current transform node
  15097. * Returns the new transform node
  15098. * @param name Name of the new clone
  15099. * @param newParent New parent for the clone
  15100. * @param doNotCloneChildren Do not clone children hierarchy
  15101. */
  15102. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15103. var _this = this;
  15104. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15105. result.name = name;
  15106. result.id = name;
  15107. if (newParent) {
  15108. result.parent = newParent;
  15109. }
  15110. if (!doNotCloneChildren) {
  15111. // Children
  15112. var directDescendants = this.getDescendants(true);
  15113. for (var index = 0; index < directDescendants.length; index++) {
  15114. var child = directDescendants[index];
  15115. if (child.clone) {
  15116. child.clone(name + "." + child.name, result);
  15117. }
  15118. }
  15119. }
  15120. return result;
  15121. };
  15122. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15123. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15124. serializationObject.type = this.getClassName();
  15125. // Parent
  15126. if (this.parent) {
  15127. serializationObject.parentId = this.parent.id;
  15128. }
  15129. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15130. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15131. }
  15132. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15133. serializationObject.isEnabled = this.isEnabled();
  15134. // Parent
  15135. if (this.parent) {
  15136. serializationObject.parentId = this.parent.id;
  15137. }
  15138. return serializationObject;
  15139. };
  15140. // Statics
  15141. /**
  15142. * Returns a new TransformNode object parsed from the source provided.
  15143. * The parameter `parsedMesh` is the source.
  15144. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15145. */
  15146. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15147. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15148. if (BABYLON.Tags) {
  15149. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15150. }
  15151. if (parsedTransformNode.localMatrix) {
  15152. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15153. }
  15154. else if (parsedTransformNode.pivotMatrix) {
  15155. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15156. }
  15157. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15158. // Parent
  15159. if (parsedTransformNode.parentId) {
  15160. transformNode._waitingParentId = parsedTransformNode.parentId;
  15161. }
  15162. return transformNode;
  15163. };
  15164. /**
  15165. * Disposes the TransformNode.
  15166. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15167. * Returns nothing.
  15168. */
  15169. TransformNode.prototype.dispose = function (doNotRecurse) {
  15170. // Animations
  15171. this.getScene().stopAnimation(this);
  15172. // Remove from scene
  15173. this.getScene().removeTransformNode(this);
  15174. if (!doNotRecurse) {
  15175. // Children
  15176. var objects = this.getDescendants(true);
  15177. for (var index = 0; index < objects.length; index++) {
  15178. objects[index].dispose();
  15179. }
  15180. }
  15181. else {
  15182. var childMeshes = this.getChildMeshes(true);
  15183. for (index = 0; index < childMeshes.length; index++) {
  15184. var child = childMeshes[index];
  15185. child.parent = null;
  15186. child.computeWorldMatrix(true);
  15187. }
  15188. }
  15189. this.onAfterWorldMatrixUpdateObservable.clear();
  15190. _super.prototype.dispose.call(this);
  15191. };
  15192. // Statics
  15193. TransformNode.BILLBOARDMODE_NONE = 0;
  15194. TransformNode.BILLBOARDMODE_X = 1;
  15195. TransformNode.BILLBOARDMODE_Y = 2;
  15196. TransformNode.BILLBOARDMODE_Z = 4;
  15197. TransformNode.BILLBOARDMODE_ALL = 7;
  15198. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15199. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15200. __decorate([
  15201. BABYLON.serializeAsVector3()
  15202. ], TransformNode.prototype, "_rotation", void 0);
  15203. __decorate([
  15204. BABYLON.serializeAsQuaternion()
  15205. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15206. __decorate([
  15207. BABYLON.serializeAsVector3()
  15208. ], TransformNode.prototype, "_scaling", void 0);
  15209. __decorate([
  15210. BABYLON.serialize()
  15211. ], TransformNode.prototype, "billboardMode", void 0);
  15212. __decorate([
  15213. BABYLON.serialize()
  15214. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15215. __decorate([
  15216. BABYLON.serialize()
  15217. ], TransformNode.prototype, "infiniteDistance", void 0);
  15218. __decorate([
  15219. BABYLON.serializeAsVector3()
  15220. ], TransformNode.prototype, "position", void 0);
  15221. return TransformNode;
  15222. }(BABYLON.Node));
  15223. BABYLON.TransformNode = TransformNode;
  15224. })(BABYLON || (BABYLON = {}));
  15225. //# sourceMappingURL=babylon.transformNode.js.map
  15226. var BABYLON;
  15227. (function (BABYLON) {
  15228. var AbstractMesh = /** @class */ (function (_super) {
  15229. __extends(AbstractMesh, _super);
  15230. // Constructor
  15231. function AbstractMesh(name, scene) {
  15232. if (scene === void 0) { scene = null; }
  15233. var _this = _super.call(this, name, scene, false) || this;
  15234. _this._facetNb = 0; // facet number
  15235. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15236. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15237. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15238. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15239. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15240. _this._subDiv = {
  15241. max: 1,
  15242. X: 1,
  15243. Y: 1,
  15244. Z: 1
  15245. };
  15246. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15247. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15248. // Events
  15249. /**
  15250. * An event triggered when this mesh collides with another one
  15251. * @type {BABYLON.Observable}
  15252. */
  15253. _this.onCollideObservable = new BABYLON.Observable();
  15254. /**
  15255. * An event triggered when the collision's position changes
  15256. * @type {BABYLON.Observable}
  15257. */
  15258. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15259. /**
  15260. * An event triggered when material is changed
  15261. * @type {BABYLON.Observable}
  15262. */
  15263. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15264. // Properties
  15265. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15266. /**
  15267. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15268. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15269. * or
  15270. * 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.
  15271. * for more info check WebGl documentations
  15272. */
  15273. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15274. /**
  15275. * 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:
  15276. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15277. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15278. * 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.
  15279. */
  15280. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15281. /**
  15282. * 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.
  15283. * The default value is -1 which means don't break the query and wait till the result.
  15284. */
  15285. _this.occlusionRetryCount = -1;
  15286. _this._occlusionInternalRetryCounter = 0;
  15287. _this._isOccluded = false;
  15288. _this._isOcclusionQueryInProgress = false;
  15289. _this.visibility = 1.0;
  15290. _this.alphaIndex = Number.MAX_VALUE;
  15291. _this.isVisible = true;
  15292. _this.isPickable = true;
  15293. _this.showBoundingBox = false;
  15294. _this.showSubMeshesBoundingBox = false;
  15295. _this.isBlocker = false;
  15296. _this.enablePointerMoveEvents = false;
  15297. _this.renderingGroupId = 0;
  15298. _this._receiveShadows = false;
  15299. _this.renderOutline = false;
  15300. _this.outlineColor = BABYLON.Color3.Red();
  15301. _this.outlineWidth = 0.02;
  15302. _this.renderOverlay = false;
  15303. _this.overlayColor = BABYLON.Color3.Red();
  15304. _this.overlayAlpha = 0.5;
  15305. _this._hasVertexAlpha = false;
  15306. _this._useVertexColors = true;
  15307. _this._computeBonesUsingShaders = true;
  15308. _this._numBoneInfluencers = 4;
  15309. _this._applyFog = true;
  15310. _this.useOctreeForRenderingSelection = true;
  15311. _this.useOctreeForPicking = true;
  15312. _this.useOctreeForCollisions = true;
  15313. _this._layerMask = 0x0FFFFFFF;
  15314. /**
  15315. * True if the mesh must be rendered in any case.
  15316. */
  15317. _this.alwaysSelectAsActiveMesh = false;
  15318. /**
  15319. * This scene's action manager
  15320. * @type {BABYLON.ActionManager}
  15321. */
  15322. _this.actionManager = null;
  15323. // Physics
  15324. _this.physicsImpostor = null;
  15325. // Collisions
  15326. _this._checkCollisions = false;
  15327. _this._collisionMask = -1;
  15328. _this._collisionGroup = -1;
  15329. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15330. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15331. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15332. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15333. // Edges
  15334. _this.edgesWidth = 1;
  15335. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15336. // Cache
  15337. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15338. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15339. _this._isDisposed = false;
  15340. _this._renderId = 0;
  15341. _this._intersectionsInProgress = new Array();
  15342. _this._unIndexed = false;
  15343. _this._lightSources = new Array();
  15344. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15345. if (collidedMesh === void 0) { collidedMesh = null; }
  15346. //TODO move this to the collision coordinator!
  15347. if (_this.getScene().workerCollisions)
  15348. newPosition.multiplyInPlace(_this._collider._radius);
  15349. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15350. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15351. _this.position.addInPlace(_this._diffPositionForCollisions);
  15352. }
  15353. if (collidedMesh) {
  15354. _this.onCollideObservable.notifyObservers(collidedMesh);
  15355. }
  15356. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15357. };
  15358. _this.getScene().addMesh(_this);
  15359. _this._resyncLightSources();
  15360. return _this;
  15361. }
  15362. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15363. get: function () {
  15364. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15365. },
  15366. enumerable: true,
  15367. configurable: true
  15368. });
  15369. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15370. get: function () {
  15371. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15372. },
  15373. enumerable: true,
  15374. configurable: true
  15375. });
  15376. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15377. get: function () {
  15378. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15379. },
  15380. enumerable: true,
  15381. configurable: true
  15382. });
  15383. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15384. get: function () {
  15385. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15386. },
  15387. enumerable: true,
  15388. configurable: true
  15389. });
  15390. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15391. get: function () {
  15392. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15393. },
  15394. enumerable: true,
  15395. configurable: true
  15396. });
  15397. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15398. /**
  15399. * Read-only : the number of facets in the mesh
  15400. */
  15401. get: function () {
  15402. return this._facetNb;
  15403. },
  15404. enumerable: true,
  15405. configurable: true
  15406. });
  15407. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15408. /**
  15409. * The number (integer) of subdivisions per axis in the partioning space
  15410. */
  15411. get: function () {
  15412. return this._partitioningSubdivisions;
  15413. },
  15414. set: function (nb) {
  15415. this._partitioningSubdivisions = nb;
  15416. },
  15417. enumerable: true,
  15418. configurable: true
  15419. });
  15420. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15421. /**
  15422. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15423. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15424. */
  15425. get: function () {
  15426. return this._partitioningBBoxRatio;
  15427. },
  15428. set: function (ratio) {
  15429. this._partitioningBBoxRatio = ratio;
  15430. },
  15431. enumerable: true,
  15432. configurable: true
  15433. });
  15434. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  15435. /**
  15436. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  15437. * Works only for updatable meshes.
  15438. * Doesn't work with multi-materials.
  15439. */
  15440. get: function () {
  15441. return this._facetDepthSort;
  15442. },
  15443. set: function (sort) {
  15444. this._facetDepthSort = sort;
  15445. },
  15446. enumerable: true,
  15447. configurable: true
  15448. });
  15449. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  15450. /**
  15451. * The location (Vector3) where the facet depth sort must be computed from.
  15452. * By default, the active camera position.
  15453. * Used only when facet depth sort is enabled.
  15454. */
  15455. get: function () {
  15456. return this._facetDepthSortFrom;
  15457. },
  15458. set: function (location) {
  15459. this._facetDepthSortFrom = location;
  15460. },
  15461. enumerable: true,
  15462. configurable: true
  15463. });
  15464. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  15465. /**
  15466. * Read-only boolean : is the feature facetData enabled ?
  15467. */
  15468. get: function () {
  15469. return this._facetDataEnabled;
  15470. },
  15471. enumerable: true,
  15472. configurable: true
  15473. });
  15474. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  15475. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  15476. return false;
  15477. }
  15478. this._markSubMeshesAsMiscDirty();
  15479. return true;
  15480. };
  15481. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  15482. set: function (callback) {
  15483. if (this._onCollideObserver) {
  15484. this.onCollideObservable.remove(this._onCollideObserver);
  15485. }
  15486. this._onCollideObserver = this.onCollideObservable.add(callback);
  15487. },
  15488. enumerable: true,
  15489. configurable: true
  15490. });
  15491. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  15492. set: function (callback) {
  15493. if (this._onCollisionPositionChangeObserver) {
  15494. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  15495. }
  15496. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  15497. },
  15498. enumerable: true,
  15499. configurable: true
  15500. });
  15501. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  15502. /**
  15503. * 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.
  15504. */
  15505. get: function () {
  15506. return this._isOccluded;
  15507. },
  15508. set: function (value) {
  15509. this._isOccluded = value;
  15510. },
  15511. enumerable: true,
  15512. configurable: true
  15513. });
  15514. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  15515. /**
  15516. * Flag to check the progress status of the query
  15517. */
  15518. get: function () {
  15519. return this._isOcclusionQueryInProgress;
  15520. },
  15521. enumerable: true,
  15522. configurable: true
  15523. });
  15524. Object.defineProperty(AbstractMesh.prototype, "material", {
  15525. get: function () {
  15526. return this._material;
  15527. },
  15528. set: function (value) {
  15529. if (this._material === value) {
  15530. return;
  15531. }
  15532. this._material = value;
  15533. if (this.onMaterialChangedObservable.hasObservers) {
  15534. this.onMaterialChangedObservable.notifyObservers(this);
  15535. }
  15536. if (!this.subMeshes) {
  15537. return;
  15538. }
  15539. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15540. var subMesh = _a[_i];
  15541. subMesh.setEffect(null);
  15542. }
  15543. },
  15544. enumerable: true,
  15545. configurable: true
  15546. });
  15547. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  15548. get: function () {
  15549. return this._receiveShadows;
  15550. },
  15551. set: function (value) {
  15552. if (this._receiveShadows === value) {
  15553. return;
  15554. }
  15555. this._receiveShadows = value;
  15556. this._markSubMeshesAsLightDirty();
  15557. },
  15558. enumerable: true,
  15559. configurable: true
  15560. });
  15561. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  15562. get: function () {
  15563. return this._hasVertexAlpha;
  15564. },
  15565. set: function (value) {
  15566. if (this._hasVertexAlpha === value) {
  15567. return;
  15568. }
  15569. this._hasVertexAlpha = value;
  15570. this._markSubMeshesAsAttributesDirty();
  15571. },
  15572. enumerable: true,
  15573. configurable: true
  15574. });
  15575. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  15576. get: function () {
  15577. return this._useVertexColors;
  15578. },
  15579. set: function (value) {
  15580. if (this._useVertexColors === value) {
  15581. return;
  15582. }
  15583. this._useVertexColors = value;
  15584. this._markSubMeshesAsAttributesDirty();
  15585. },
  15586. enumerable: true,
  15587. configurable: true
  15588. });
  15589. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  15590. get: function () {
  15591. return this._computeBonesUsingShaders;
  15592. },
  15593. set: function (value) {
  15594. if (this._computeBonesUsingShaders === value) {
  15595. return;
  15596. }
  15597. this._computeBonesUsingShaders = value;
  15598. this._markSubMeshesAsAttributesDirty();
  15599. },
  15600. enumerable: true,
  15601. configurable: true
  15602. });
  15603. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  15604. get: function () {
  15605. return this._numBoneInfluencers;
  15606. },
  15607. set: function (value) {
  15608. if (this._numBoneInfluencers === value) {
  15609. return;
  15610. }
  15611. this._numBoneInfluencers = value;
  15612. this._markSubMeshesAsAttributesDirty();
  15613. },
  15614. enumerable: true,
  15615. configurable: true
  15616. });
  15617. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  15618. get: function () {
  15619. return this._applyFog;
  15620. },
  15621. set: function (value) {
  15622. if (this._applyFog === value) {
  15623. return;
  15624. }
  15625. this._applyFog = value;
  15626. this._markSubMeshesAsMiscDirty();
  15627. },
  15628. enumerable: true,
  15629. configurable: true
  15630. });
  15631. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  15632. get: function () {
  15633. return this._layerMask;
  15634. },
  15635. set: function (value) {
  15636. if (value === this._layerMask) {
  15637. return;
  15638. }
  15639. this._layerMask = value;
  15640. this._resyncLightSources();
  15641. },
  15642. enumerable: true,
  15643. configurable: true
  15644. });
  15645. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  15646. get: function () {
  15647. return this._collisionMask;
  15648. },
  15649. set: function (mask) {
  15650. this._collisionMask = !isNaN(mask) ? mask : -1;
  15651. },
  15652. enumerable: true,
  15653. configurable: true
  15654. });
  15655. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  15656. get: function () {
  15657. return this._collisionGroup;
  15658. },
  15659. set: function (mask) {
  15660. this._collisionGroup = !isNaN(mask) ? mask : -1;
  15661. },
  15662. enumerable: true,
  15663. configurable: true
  15664. });
  15665. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  15666. get: function () {
  15667. return null;
  15668. },
  15669. enumerable: true,
  15670. configurable: true
  15671. });
  15672. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  15673. get: function () {
  15674. return this._skeleton;
  15675. },
  15676. set: function (value) {
  15677. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  15678. this._skeleton._unregisterMeshWithPoseMatrix(this);
  15679. }
  15680. if (value && value.needInitialSkinMatrix) {
  15681. value._registerMeshWithPoseMatrix(this);
  15682. }
  15683. this._skeleton = value;
  15684. if (!this._skeleton) {
  15685. this._bonesTransformMatrices = null;
  15686. }
  15687. this._markSubMeshesAsAttributesDirty();
  15688. },
  15689. enumerable: true,
  15690. configurable: true
  15691. });
  15692. /**
  15693. * Boolean : true if the mesh has been disposed.
  15694. */
  15695. AbstractMesh.prototype.isDisposed = function () {
  15696. return this._isDisposed;
  15697. };
  15698. /**
  15699. * Returns the string "AbstractMesh"
  15700. */
  15701. AbstractMesh.prototype.getClassName = function () {
  15702. return "AbstractMesh";
  15703. };
  15704. /**
  15705. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15706. */
  15707. AbstractMesh.prototype.toString = function (fullDetails) {
  15708. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  15709. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  15710. if (this._skeleton) {
  15711. ret += ", skeleton: " + this._skeleton.name;
  15712. }
  15713. if (fullDetails) {
  15714. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  15715. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  15716. }
  15717. return ret;
  15718. };
  15719. AbstractMesh.prototype._rebuild = function () {
  15720. if (this._occlusionQuery) {
  15721. this._occlusionQuery = null;
  15722. }
  15723. if (this._edgesRenderer) {
  15724. this._edgesRenderer._rebuild();
  15725. }
  15726. if (!this.subMeshes) {
  15727. return;
  15728. }
  15729. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15730. var subMesh = _a[_i];
  15731. subMesh._rebuild();
  15732. }
  15733. };
  15734. AbstractMesh.prototype._resyncLightSources = function () {
  15735. this._lightSources.length = 0;
  15736. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  15737. var light = _a[_i];
  15738. if (!light.isEnabled()) {
  15739. continue;
  15740. }
  15741. if (light.canAffectMesh(this)) {
  15742. this._lightSources.push(light);
  15743. }
  15744. }
  15745. this._markSubMeshesAsLightDirty();
  15746. };
  15747. AbstractMesh.prototype._resyncLighSource = function (light) {
  15748. var isIn = light.isEnabled() && light.canAffectMesh(this);
  15749. var index = this._lightSources.indexOf(light);
  15750. if (index === -1) {
  15751. if (!isIn) {
  15752. return;
  15753. }
  15754. this._lightSources.push(light);
  15755. }
  15756. else {
  15757. if (isIn) {
  15758. return;
  15759. }
  15760. this._lightSources.splice(index, 1);
  15761. }
  15762. this._markSubMeshesAsLightDirty();
  15763. };
  15764. AbstractMesh.prototype._removeLightSource = function (light) {
  15765. var index = this._lightSources.indexOf(light);
  15766. if (index === -1) {
  15767. return;
  15768. }
  15769. this._lightSources.splice(index, 1);
  15770. };
  15771. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  15772. if (!this.subMeshes) {
  15773. return;
  15774. }
  15775. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15776. var subMesh = _a[_i];
  15777. if (subMesh._materialDefines) {
  15778. func(subMesh._materialDefines);
  15779. }
  15780. }
  15781. };
  15782. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  15783. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  15784. };
  15785. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  15786. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  15787. };
  15788. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  15789. if (!this.subMeshes) {
  15790. return;
  15791. }
  15792. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15793. var subMesh = _a[_i];
  15794. var material = subMesh.getMaterial();
  15795. if (material) {
  15796. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  15797. }
  15798. }
  15799. };
  15800. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  15801. /**
  15802. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15803. * Default : (1.0, 1.0, 1.0)
  15804. */
  15805. get: function () {
  15806. return this._scaling;
  15807. },
  15808. /**
  15809. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15810. * Default : (1.0, 1.0, 1.0)
  15811. */
  15812. set: function (newScaling) {
  15813. this._scaling = newScaling;
  15814. if (this.physicsImpostor) {
  15815. this.physicsImpostor.forceUpdate();
  15816. }
  15817. },
  15818. enumerable: true,
  15819. configurable: true
  15820. });
  15821. // Methods
  15822. /**
  15823. * Disables the mesh edger rendering mode.
  15824. * Returns the AbstractMesh.
  15825. */
  15826. AbstractMesh.prototype.disableEdgesRendering = function () {
  15827. if (this._edgesRenderer) {
  15828. this._edgesRenderer.dispose();
  15829. this._edgesRenderer = null;
  15830. }
  15831. return this;
  15832. };
  15833. /**
  15834. * Enables the edge rendering mode on the mesh.
  15835. * This mode makes the mesh edges visible.
  15836. * Returns the AbstractMesh.
  15837. */
  15838. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  15839. if (epsilon === void 0) { epsilon = 0.95; }
  15840. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  15841. this.disableEdgesRendering();
  15842. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  15843. return this;
  15844. };
  15845. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  15846. /**
  15847. * Returns true if the mesh is blocked. Used by the class Mesh.
  15848. * Returns the boolean `false` by default.
  15849. */
  15850. get: function () {
  15851. return false;
  15852. },
  15853. enumerable: true,
  15854. configurable: true
  15855. });
  15856. /**
  15857. * Returns the mesh itself by default, used by the class Mesh.
  15858. * Returned type : AbstractMesh
  15859. */
  15860. AbstractMesh.prototype.getLOD = function (camera) {
  15861. return this;
  15862. };
  15863. /**
  15864. * Returns 0 by default, used by the class Mesh.
  15865. * Returns an integer.
  15866. */
  15867. AbstractMesh.prototype.getTotalVertices = function () {
  15868. return 0;
  15869. };
  15870. /**
  15871. * Returns null by default, used by the class Mesh.
  15872. * Returned type : integer array
  15873. */
  15874. AbstractMesh.prototype.getIndices = function () {
  15875. return null;
  15876. };
  15877. /**
  15878. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  15879. * Returned type : float array or Float32Array
  15880. */
  15881. AbstractMesh.prototype.getVerticesData = function (kind) {
  15882. return null;
  15883. };
  15884. /**
  15885. * Sets the vertex data of the mesh geometry for the requested `kind`.
  15886. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  15887. * The `data` are either a numeric array either a Float32Array.
  15888. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  15889. * 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).
  15890. * Note that a new underlying VertexBuffer object is created each call.
  15891. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  15892. *
  15893. * Possible `kind` values :
  15894. * - BABYLON.VertexBuffer.PositionKind
  15895. * - BABYLON.VertexBuffer.UVKind
  15896. * - BABYLON.VertexBuffer.UV2Kind
  15897. * - BABYLON.VertexBuffer.UV3Kind
  15898. * - BABYLON.VertexBuffer.UV4Kind
  15899. * - BABYLON.VertexBuffer.UV5Kind
  15900. * - BABYLON.VertexBuffer.UV6Kind
  15901. * - BABYLON.VertexBuffer.ColorKind
  15902. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15903. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15904. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15905. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15906. *
  15907. * Returns the Mesh.
  15908. */
  15909. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15910. return this;
  15911. };
  15912. /**
  15913. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  15914. * If the mesh has no geometry, it is simply returned as it is.
  15915. * The `data` are either a numeric array either a Float32Array.
  15916. * No new underlying VertexBuffer object is created.
  15917. * 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.
  15918. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  15919. *
  15920. * Possible `kind` values :
  15921. * - BABYLON.VertexBuffer.PositionKind
  15922. * - BABYLON.VertexBuffer.UVKind
  15923. * - BABYLON.VertexBuffer.UV2Kind
  15924. * - BABYLON.VertexBuffer.UV3Kind
  15925. * - BABYLON.VertexBuffer.UV4Kind
  15926. * - BABYLON.VertexBuffer.UV5Kind
  15927. * - BABYLON.VertexBuffer.UV6Kind
  15928. * - BABYLON.VertexBuffer.ColorKind
  15929. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15930. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15931. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15932. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15933. *
  15934. * Returns the Mesh.
  15935. */
  15936. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15937. return this;
  15938. };
  15939. /**
  15940. * Sets the mesh indices.
  15941. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  15942. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  15943. * This method creates a new index buffer each call.
  15944. * Returns the Mesh.
  15945. */
  15946. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  15947. return this;
  15948. };
  15949. /** Returns false by default, used by the class Mesh.
  15950. * Returns a boolean
  15951. */
  15952. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  15953. return false;
  15954. };
  15955. /**
  15956. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  15957. * Returns a BoundingInfo
  15958. */
  15959. AbstractMesh.prototype.getBoundingInfo = function () {
  15960. if (this._masterMesh) {
  15961. return this._masterMesh.getBoundingInfo();
  15962. }
  15963. if (!this._boundingInfo) {
  15964. // this._boundingInfo is being created here
  15965. this._updateBoundingInfo();
  15966. }
  15967. // cannot be null.
  15968. return this._boundingInfo;
  15969. };
  15970. /**
  15971. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  15972. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  15973. */
  15974. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  15975. if (includeDescendants === void 0) { includeDescendants = true; }
  15976. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  15977. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  15978. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  15979. if (maxDimension === 0) {
  15980. return this;
  15981. }
  15982. var scale = 1 / maxDimension;
  15983. this.scaling.scaleInPlace(scale);
  15984. return this;
  15985. };
  15986. /**
  15987. * Sets a mesh new object BoundingInfo.
  15988. * Returns the AbstractMesh.
  15989. */
  15990. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  15991. this._boundingInfo = boundingInfo;
  15992. return this;
  15993. };
  15994. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  15995. get: function () {
  15996. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  15997. },
  15998. enumerable: true,
  15999. configurable: true
  16000. });
  16001. AbstractMesh.prototype._preActivate = function () {
  16002. };
  16003. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16004. };
  16005. AbstractMesh.prototype._activate = function (renderId) {
  16006. this._renderId = renderId;
  16007. };
  16008. /**
  16009. * Returns the latest update of the World matrix
  16010. * Returns a Matrix.
  16011. */
  16012. AbstractMesh.prototype.getWorldMatrix = function () {
  16013. if (this._masterMesh) {
  16014. return this._masterMesh.getWorldMatrix();
  16015. }
  16016. return _super.prototype.getWorldMatrix.call(this);
  16017. };
  16018. /**
  16019. * Returns the latest update of the World matrix determinant.
  16020. */
  16021. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16022. if (this._masterMesh) {
  16023. return this._masterMesh._getWorldMatrixDeterminant();
  16024. }
  16025. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16026. };
  16027. // ================================== Point of View Movement =================================
  16028. /**
  16029. * Perform relative position change from the point of view of behind the front of the mesh.
  16030. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16031. * Supports definition of mesh facing forward or backward.
  16032. * @param {number} amountRight
  16033. * @param {number} amountUp
  16034. * @param {number} amountForward
  16035. *
  16036. * Returns the AbstractMesh.
  16037. */
  16038. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16039. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16040. return this;
  16041. };
  16042. /**
  16043. * Calculate relative position change from the point of view of behind the front of the mesh.
  16044. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16045. * Supports definition of mesh facing forward or backward.
  16046. * @param {number} amountRight
  16047. * @param {number} amountUp
  16048. * @param {number} amountForward
  16049. *
  16050. * Returns a new Vector3.
  16051. */
  16052. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16053. var rotMatrix = new BABYLON.Matrix();
  16054. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16055. rotQuaternion.toRotationMatrix(rotMatrix);
  16056. var translationDelta = BABYLON.Vector3.Zero();
  16057. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16058. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16059. return translationDelta;
  16060. };
  16061. // ================================== Point of View Rotation =================================
  16062. /**
  16063. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16064. * Supports definition of mesh facing forward or backward.
  16065. * @param {number} flipBack
  16066. * @param {number} twirlClockwise
  16067. * @param {number} tiltRight
  16068. *
  16069. * Returns the AbstractMesh.
  16070. */
  16071. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16072. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16073. return this;
  16074. };
  16075. /**
  16076. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16077. * Supports definition of mesh facing forward or backward.
  16078. * @param {number} flipBack
  16079. * @param {number} twirlClockwise
  16080. * @param {number} tiltRight
  16081. *
  16082. * Returns a new Vector3.
  16083. */
  16084. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16085. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16086. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16087. };
  16088. /**
  16089. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16090. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16091. */
  16092. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16093. if (includeDescendants === void 0) { includeDescendants = true; }
  16094. this.computeWorldMatrix(true);
  16095. var min;
  16096. var max;
  16097. var boundingInfo = this.getBoundingInfo();
  16098. if (!this.subMeshes) {
  16099. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16100. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16101. }
  16102. else {
  16103. min = boundingInfo.boundingBox.minimumWorld;
  16104. max = boundingInfo.boundingBox.maximumWorld;
  16105. }
  16106. if (includeDescendants) {
  16107. var descendants = this.getDescendants(false);
  16108. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16109. var descendant = descendants_1[_i];
  16110. var childMesh = descendant;
  16111. childMesh.computeWorldMatrix(true);
  16112. //make sure we have the needed params to get mix and max
  16113. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16114. continue;
  16115. }
  16116. var childBoundingInfo = childMesh.getBoundingInfo();
  16117. var boundingBox = childBoundingInfo.boundingBox;
  16118. var minBox = boundingBox.minimumWorld;
  16119. var maxBox = boundingBox.maximumWorld;
  16120. BABYLON.Tools.CheckExtends(minBox, min, max);
  16121. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16122. }
  16123. }
  16124. return {
  16125. min: min,
  16126. max: max
  16127. };
  16128. };
  16129. /**
  16130. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16131. * Returns the AbstractMesh.
  16132. */
  16133. AbstractMesh.prototype._updateBoundingInfo = function () {
  16134. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16135. this._boundingInfo.update(this.worldMatrixFromCache);
  16136. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16137. return this;
  16138. };
  16139. /**
  16140. * Update a mesh's children BoundingInfo objects only.
  16141. * Returns the AbstractMesh.
  16142. */
  16143. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16144. if (!this.subMeshes) {
  16145. return this;
  16146. }
  16147. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16148. var subMesh = this.subMeshes[subIndex];
  16149. if (!subMesh.IsGlobal) {
  16150. subMesh.updateBoundingInfo(matrix);
  16151. }
  16152. }
  16153. return this;
  16154. };
  16155. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16156. // Bounding info
  16157. this._updateBoundingInfo();
  16158. };
  16159. /**
  16160. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16161. * A mesh is in the frustum if its bounding box intersects the frustum.
  16162. * Boolean returned.
  16163. */
  16164. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16165. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16166. };
  16167. /**
  16168. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16169. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16170. * Boolean returned.
  16171. */
  16172. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16173. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16174. ;
  16175. };
  16176. /**
  16177. * True if the mesh intersects another mesh or a SolidParticle object.
  16178. * 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)
  16179. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16180. * Returns a boolean.
  16181. */
  16182. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16183. if (precise === void 0) { precise = false; }
  16184. if (!this._boundingInfo || !mesh._boundingInfo) {
  16185. return false;
  16186. }
  16187. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16188. return true;
  16189. }
  16190. if (includeDescendants) {
  16191. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16192. var child = _a[_i];
  16193. if (child.intersectsMesh(mesh, precise, true)) {
  16194. return true;
  16195. }
  16196. }
  16197. }
  16198. return false;
  16199. };
  16200. /**
  16201. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16202. * Returns a boolean.
  16203. */
  16204. AbstractMesh.prototype.intersectsPoint = function (point) {
  16205. if (!this._boundingInfo) {
  16206. return false;
  16207. }
  16208. return this._boundingInfo.intersectsPoint(point);
  16209. };
  16210. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16211. return this.physicsImpostor;
  16212. };
  16213. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16214. if (camera === void 0) { camera = null; }
  16215. if (!camera) {
  16216. camera = this.getScene().activeCamera;
  16217. }
  16218. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16219. };
  16220. /**
  16221. * Returns the distance from the mesh to the active camera.
  16222. * Returns a float.
  16223. */
  16224. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16225. if (camera === void 0) { camera = null; }
  16226. if (!camera) {
  16227. camera = this.getScene().activeCamera;
  16228. }
  16229. return this.absolutePosition.subtract(camera.position).length();
  16230. };
  16231. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16232. if (!this.physicsImpostor) {
  16233. return this;
  16234. }
  16235. this.physicsImpostor.applyImpulse(force, contactPoint);
  16236. return this;
  16237. };
  16238. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16239. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16240. return this;
  16241. }
  16242. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16243. mainPivot: pivot1,
  16244. connectedPivot: pivot2,
  16245. nativeParams: options
  16246. });
  16247. return this;
  16248. };
  16249. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16250. // Collisions
  16251. /**
  16252. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16253. * Default `false`.
  16254. */
  16255. get: function () {
  16256. return this._checkCollisions;
  16257. },
  16258. set: function (collisionEnabled) {
  16259. this._checkCollisions = collisionEnabled;
  16260. if (this.getScene().workerCollisions) {
  16261. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16262. }
  16263. },
  16264. enumerable: true,
  16265. configurable: true
  16266. });
  16267. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16268. /**
  16269. * Gets Collider object used to compute collisions (not physics)
  16270. */
  16271. get: function () {
  16272. return this._collider;
  16273. },
  16274. enumerable: true,
  16275. configurable: true
  16276. });
  16277. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16278. var globalPosition = this.getAbsolutePosition();
  16279. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16280. if (!this._collider) {
  16281. this._collider = new BABYLON.Collider();
  16282. }
  16283. this._collider._radius = this.ellipsoid;
  16284. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16285. return this;
  16286. };
  16287. // Submeshes octree
  16288. /**
  16289. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16290. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16291. * Returns an Octree of submeshes.
  16292. */
  16293. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16294. if (maxCapacity === void 0) { maxCapacity = 64; }
  16295. if (maxDepth === void 0) { maxDepth = 2; }
  16296. if (!this._submeshesOctree) {
  16297. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16298. }
  16299. this.computeWorldMatrix(true);
  16300. var boundingInfo = this.getBoundingInfo();
  16301. // Update octree
  16302. var bbox = boundingInfo.boundingBox;
  16303. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16304. return this._submeshesOctree;
  16305. };
  16306. // Collisions
  16307. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16308. this._generatePointsArray();
  16309. if (!this._positions) {
  16310. return this;
  16311. }
  16312. // Transformation
  16313. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16314. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16315. subMesh._lastColliderWorldVertices = [];
  16316. subMesh._trianglePlanes = [];
  16317. var start = subMesh.verticesStart;
  16318. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16319. for (var i = start; i < end; i++) {
  16320. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16321. }
  16322. }
  16323. // Collide
  16324. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16325. if (collider.collisionFound) {
  16326. collider.collidedMesh = this;
  16327. }
  16328. return this;
  16329. };
  16330. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16331. var subMeshes;
  16332. var len;
  16333. // Octrees
  16334. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16335. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16336. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16337. len = intersections.length;
  16338. subMeshes = intersections.data;
  16339. }
  16340. else {
  16341. subMeshes = this.subMeshes;
  16342. len = subMeshes.length;
  16343. }
  16344. for (var index = 0; index < len; index++) {
  16345. var subMesh = subMeshes[index];
  16346. // Bounding test
  16347. if (len > 1 && !subMesh._checkCollision(collider))
  16348. continue;
  16349. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16350. }
  16351. return this;
  16352. };
  16353. AbstractMesh.prototype._checkCollision = function (collider) {
  16354. // Bounding box test
  16355. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16356. return this;
  16357. // Transformation matrix
  16358. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16359. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16360. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16361. return this;
  16362. };
  16363. // Picking
  16364. AbstractMesh.prototype._generatePointsArray = function () {
  16365. return false;
  16366. };
  16367. /**
  16368. * Checks if the passed Ray intersects with the mesh.
  16369. * Returns an object PickingInfo.
  16370. */
  16371. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16372. var pickingInfo = new BABYLON.PickingInfo();
  16373. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16374. return pickingInfo;
  16375. }
  16376. if (!this._generatePointsArray()) {
  16377. return pickingInfo;
  16378. }
  16379. var intersectInfo = null;
  16380. // Octrees
  16381. var subMeshes;
  16382. var len;
  16383. if (this._submeshesOctree && this.useOctreeForPicking) {
  16384. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16385. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16386. len = intersections.length;
  16387. subMeshes = intersections.data;
  16388. }
  16389. else {
  16390. subMeshes = this.subMeshes;
  16391. len = subMeshes.length;
  16392. }
  16393. for (var index = 0; index < len; index++) {
  16394. var subMesh = subMeshes[index];
  16395. // Bounding test
  16396. if (len > 1 && !subMesh.canIntersects(ray))
  16397. continue;
  16398. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16399. if (currentIntersectInfo) {
  16400. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16401. intersectInfo = currentIntersectInfo;
  16402. intersectInfo.subMeshId = index;
  16403. if (fastCheck) {
  16404. break;
  16405. }
  16406. }
  16407. }
  16408. }
  16409. if (intersectInfo) {
  16410. // Get picked point
  16411. var world = this.getWorldMatrix();
  16412. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  16413. var direction = ray.direction.clone();
  16414. direction = direction.scale(intersectInfo.distance);
  16415. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  16416. var pickedPoint = worldOrigin.add(worldDirection);
  16417. // Return result
  16418. pickingInfo.hit = true;
  16419. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  16420. pickingInfo.pickedPoint = pickedPoint;
  16421. pickingInfo.pickedMesh = this;
  16422. pickingInfo.bu = intersectInfo.bu || 0;
  16423. pickingInfo.bv = intersectInfo.bv || 0;
  16424. pickingInfo.faceId = intersectInfo.faceId;
  16425. pickingInfo.subMeshId = intersectInfo.subMeshId;
  16426. return pickingInfo;
  16427. }
  16428. return pickingInfo;
  16429. };
  16430. /**
  16431. * Clones the mesh, used by the class Mesh.
  16432. * Just returns `null` for an AbstractMesh.
  16433. */
  16434. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16435. return null;
  16436. };
  16437. /**
  16438. * Disposes all the mesh submeshes.
  16439. * Returns the AbstractMesh.
  16440. */
  16441. AbstractMesh.prototype.releaseSubMeshes = function () {
  16442. if (this.subMeshes) {
  16443. while (this.subMeshes.length) {
  16444. this.subMeshes[0].dispose();
  16445. }
  16446. }
  16447. else {
  16448. this.subMeshes = new Array();
  16449. }
  16450. return this;
  16451. };
  16452. /**
  16453. * Disposes the AbstractMesh.
  16454. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16455. * Returns nothing.
  16456. */
  16457. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16458. var _this = this;
  16459. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16460. var index;
  16461. // Action manager
  16462. if (this.actionManager !== undefined && this.actionManager !== null) {
  16463. this.actionManager.dispose();
  16464. this.actionManager = null;
  16465. }
  16466. // Skeleton
  16467. this.skeleton = null;
  16468. // Physics
  16469. if (this.physicsImpostor) {
  16470. this.physicsImpostor.dispose();
  16471. }
  16472. // Intersections in progress
  16473. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  16474. var other = this._intersectionsInProgress[index];
  16475. var pos = other._intersectionsInProgress.indexOf(this);
  16476. other._intersectionsInProgress.splice(pos, 1);
  16477. }
  16478. this._intersectionsInProgress = [];
  16479. // Lights
  16480. var lights = this.getScene().lights;
  16481. lights.forEach(function (light) {
  16482. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  16483. if (meshIndex !== -1) {
  16484. light.includedOnlyMeshes.splice(meshIndex, 1);
  16485. }
  16486. meshIndex = light.excludedMeshes.indexOf(_this);
  16487. if (meshIndex !== -1) {
  16488. light.excludedMeshes.splice(meshIndex, 1);
  16489. }
  16490. // Shadow generators
  16491. var generator = light.getShadowGenerator();
  16492. if (generator) {
  16493. var shadowMap = generator.getShadowMap();
  16494. if (shadowMap && shadowMap.renderList) {
  16495. meshIndex = shadowMap.renderList.indexOf(_this);
  16496. if (meshIndex !== -1) {
  16497. shadowMap.renderList.splice(meshIndex, 1);
  16498. }
  16499. }
  16500. }
  16501. });
  16502. // Edges
  16503. if (this._edgesRenderer) {
  16504. this._edgesRenderer.dispose();
  16505. this._edgesRenderer = null;
  16506. }
  16507. // SubMeshes
  16508. if (this.getClassName() !== "InstancedMesh") {
  16509. this.releaseSubMeshes();
  16510. }
  16511. // Octree
  16512. var sceneOctree = this.getScene().selectionOctree;
  16513. if (sceneOctree !== undefined && sceneOctree !== null) {
  16514. var index = sceneOctree.dynamicContent.indexOf(this);
  16515. if (index !== -1) {
  16516. sceneOctree.dynamicContent.splice(index, 1);
  16517. }
  16518. }
  16519. // Query
  16520. var engine = this.getScene().getEngine();
  16521. if (this._occlusionQuery) {
  16522. this._isOcclusionQueryInProgress = false;
  16523. engine.deleteQuery(this._occlusionQuery);
  16524. this._occlusionQuery = null;
  16525. }
  16526. // Engine
  16527. engine.wipeCaches();
  16528. // Remove from scene
  16529. this.getScene().removeMesh(this);
  16530. if (disposeMaterialAndTextures) {
  16531. if (this.material) {
  16532. this.material.dispose(false, true);
  16533. }
  16534. }
  16535. if (!doNotRecurse) {
  16536. // Particles
  16537. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  16538. if (this.getScene().particleSystems[index].emitter === this) {
  16539. this.getScene().particleSystems[index].dispose();
  16540. index--;
  16541. }
  16542. }
  16543. }
  16544. // facet data
  16545. if (this._facetDataEnabled) {
  16546. this.disableFacetData();
  16547. }
  16548. this.onAfterWorldMatrixUpdateObservable.clear();
  16549. this.onCollideObservable.clear();
  16550. this.onCollisionPositionChangeObservable.clear();
  16551. this._isDisposed = true;
  16552. _super.prototype.dispose.call(this, doNotRecurse);
  16553. };
  16554. /**
  16555. * Adds the passed mesh as a child to the current mesh.
  16556. * Returns the AbstractMesh.
  16557. */
  16558. AbstractMesh.prototype.addChild = function (mesh) {
  16559. mesh.setParent(this);
  16560. return this;
  16561. };
  16562. /**
  16563. * Removes the passed mesh from the current mesh children list.
  16564. * Returns the AbstractMesh.
  16565. */
  16566. AbstractMesh.prototype.removeChild = function (mesh) {
  16567. mesh.setParent(null);
  16568. return this;
  16569. };
  16570. // Facet data
  16571. /**
  16572. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  16573. * Returns the AbstractMesh.
  16574. */
  16575. AbstractMesh.prototype._initFacetData = function () {
  16576. if (!this._facetNormals) {
  16577. this._facetNormals = new Array();
  16578. }
  16579. if (!this._facetPositions) {
  16580. this._facetPositions = new Array();
  16581. }
  16582. if (!this._facetPartitioning) {
  16583. this._facetPartitioning = new Array();
  16584. }
  16585. this._facetNb = (this.getIndices().length / 3) | 0;
  16586. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  16587. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  16588. for (var f = 0; f < this._facetNb; f++) {
  16589. this._facetNormals[f] = BABYLON.Vector3.Zero();
  16590. this._facetPositions[f] = BABYLON.Vector3.Zero();
  16591. }
  16592. this._facetDataEnabled = true;
  16593. return this;
  16594. };
  16595. /**
  16596. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  16597. * This method can be called within the render loop.
  16598. * 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.
  16599. * Returns the AbstractMesh.
  16600. */
  16601. AbstractMesh.prototype.updateFacetData = function () {
  16602. if (!this._facetDataEnabled) {
  16603. this._initFacetData();
  16604. }
  16605. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16606. var indices = this.getIndices();
  16607. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16608. var bInfo = this.getBoundingInfo();
  16609. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  16610. // init arrays, matrix and sort function on first call
  16611. this._facetDepthSortEnabled = true;
  16612. if (indices instanceof Uint16Array) {
  16613. this._depthSortedIndices = new Uint16Array(indices);
  16614. }
  16615. else if (indices instanceof Uint32Array) {
  16616. this._depthSortedIndices = new Uint32Array(indices);
  16617. }
  16618. else {
  16619. var needs32bits = false;
  16620. for (var i = 0; i < indices.length; i++) {
  16621. if (indices[i] > 65535) {
  16622. needs32bits = true;
  16623. break;
  16624. }
  16625. }
  16626. if (needs32bits) {
  16627. this._depthSortedIndices = new Uint32Array(indices);
  16628. }
  16629. else {
  16630. this._depthSortedIndices = new Uint16Array(indices);
  16631. }
  16632. }
  16633. this._facetDepthSortFunction = function (f1, f2) {
  16634. return (f2.sqDistance - f1.sqDistance);
  16635. };
  16636. if (!this._facetDepthSortFrom) {
  16637. var camera = this.getScene().activeCamera;
  16638. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  16639. }
  16640. this._depthSortedFacets = [];
  16641. for (var f = 0; f < this._facetNb; f++) {
  16642. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  16643. this._depthSortedFacets.push(depthSortedFacet);
  16644. }
  16645. this._invertedMatrix = BABYLON.Matrix.Identity();
  16646. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  16647. }
  16648. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  16649. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  16650. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  16651. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  16652. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  16653. this._subDiv.max = this._partitioningSubdivisions;
  16654. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  16655. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  16656. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  16657. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  16658. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  16659. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  16660. // set the parameters for ComputeNormals()
  16661. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  16662. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  16663. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  16664. this._facetParameters.bInfo = bInfo;
  16665. this._facetParameters.bbSize = this._bbSize;
  16666. this._facetParameters.subDiv = this._subDiv;
  16667. this._facetParameters.ratio = this.partitioningBBoxRatio;
  16668. this._facetParameters.depthSort = this._facetDepthSort;
  16669. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16670. this.computeWorldMatrix(true);
  16671. this._worldMatrix.invertToRef(this._invertedMatrix);
  16672. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  16673. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  16674. }
  16675. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  16676. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  16677. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16678. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  16679. var l = (this._depthSortedIndices.length / 3) | 0;
  16680. for (var f = 0; f < l; f++) {
  16681. var sind = this._depthSortedFacets[f].ind;
  16682. this._depthSortedIndices[f * 3] = indices[sind];
  16683. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  16684. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  16685. }
  16686. this.updateIndices(this._depthSortedIndices);
  16687. }
  16688. return this;
  16689. };
  16690. /**
  16691. * Returns the facetLocalNormals array.
  16692. * The normals are expressed in the mesh local space.
  16693. */
  16694. AbstractMesh.prototype.getFacetLocalNormals = function () {
  16695. if (!this._facetNormals) {
  16696. this.updateFacetData();
  16697. }
  16698. return this._facetNormals;
  16699. };
  16700. /**
  16701. * Returns the facetLocalPositions array.
  16702. * The facet positions are expressed in the mesh local space.
  16703. */
  16704. AbstractMesh.prototype.getFacetLocalPositions = function () {
  16705. if (!this._facetPositions) {
  16706. this.updateFacetData();
  16707. }
  16708. return this._facetPositions;
  16709. };
  16710. /**
  16711. * Returns the facetLocalPartioning array.
  16712. */
  16713. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  16714. if (!this._facetPartitioning) {
  16715. this.updateFacetData();
  16716. }
  16717. return this._facetPartitioning;
  16718. };
  16719. /**
  16720. * Returns the i-th facet position in the world system.
  16721. * This method allocates a new Vector3 per call.
  16722. */
  16723. AbstractMesh.prototype.getFacetPosition = function (i) {
  16724. var pos = BABYLON.Vector3.Zero();
  16725. this.getFacetPositionToRef(i, pos);
  16726. return pos;
  16727. };
  16728. /**
  16729. * Sets the reference Vector3 with the i-th facet position in the world system.
  16730. * Returns the AbstractMesh.
  16731. */
  16732. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  16733. var localPos = (this.getFacetLocalPositions())[i];
  16734. var world = this.getWorldMatrix();
  16735. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  16736. return this;
  16737. };
  16738. /**
  16739. * Returns the i-th facet normal in the world system.
  16740. * This method allocates a new Vector3 per call.
  16741. */
  16742. AbstractMesh.prototype.getFacetNormal = function (i) {
  16743. var norm = BABYLON.Vector3.Zero();
  16744. this.getFacetNormalToRef(i, norm);
  16745. return norm;
  16746. };
  16747. /**
  16748. * Sets the reference Vector3 with the i-th facet normal in the world system.
  16749. * Returns the AbstractMesh.
  16750. */
  16751. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  16752. var localNorm = (this.getFacetLocalNormals())[i];
  16753. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  16754. return this;
  16755. };
  16756. /**
  16757. * 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).
  16758. */
  16759. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  16760. var bInfo = this.getBoundingInfo();
  16761. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  16762. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  16763. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  16764. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  16765. return null;
  16766. }
  16767. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  16768. };
  16769. /**
  16770. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  16771. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  16772. * 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.
  16773. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16774. * 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.
  16775. */
  16776. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  16777. if (checkFace === void 0) { checkFace = false; }
  16778. if (facing === void 0) { facing = true; }
  16779. var world = this.getWorldMatrix();
  16780. var invMat = BABYLON.Tmp.Matrix[5];
  16781. world.invertToRef(invMat);
  16782. var invVect = BABYLON.Tmp.Vector3[8];
  16783. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  16784. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  16785. if (projected) {
  16786. // tranform the local computed projected vector to world coordinates
  16787. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  16788. }
  16789. return closest;
  16790. };
  16791. /**
  16792. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  16793. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local 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.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  16799. if (checkFace === void 0) { checkFace = false; }
  16800. if (facing === void 0) { facing = true; }
  16801. var closest = null;
  16802. var tmpx = 0.0;
  16803. var tmpy = 0.0;
  16804. var tmpz = 0.0;
  16805. var d = 0.0; // tmp dot facet normal * facet position
  16806. var t0 = 0.0;
  16807. var projx = 0.0;
  16808. var projy = 0.0;
  16809. var projz = 0.0;
  16810. // Get all the facets in the same partitioning block than (x, y, z)
  16811. var facetPositions = this.getFacetLocalPositions();
  16812. var facetNormals = this.getFacetLocalNormals();
  16813. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  16814. if (!facetsInBlock) {
  16815. return null;
  16816. }
  16817. // Get the closest facet to (x, y, z)
  16818. var shortest = Number.MAX_VALUE; // init distance vars
  16819. var tmpDistance = shortest;
  16820. var fib; // current facet in the block
  16821. var norm; // current facet normal
  16822. var p0; // current facet barycenter position
  16823. // loop on all the facets in the current partitioning block
  16824. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  16825. fib = facetsInBlock[idx];
  16826. norm = facetNormals[fib];
  16827. p0 = facetPositions[fib];
  16828. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  16829. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  16830. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  16831. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  16832. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  16833. projx = x + norm.x * t0;
  16834. projy = y + norm.y * t0;
  16835. projz = z + norm.z * t0;
  16836. tmpx = projx - x;
  16837. tmpy = projy - y;
  16838. tmpz = projz - z;
  16839. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  16840. if (tmpDistance < shortest) {
  16841. shortest = tmpDistance;
  16842. closest = fib;
  16843. if (projected) {
  16844. projected.x = projx;
  16845. projected.y = projy;
  16846. projected.z = projz;
  16847. }
  16848. }
  16849. }
  16850. }
  16851. return closest;
  16852. };
  16853. /**
  16854. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  16855. */
  16856. AbstractMesh.prototype.getFacetDataParameters = function () {
  16857. return this._facetParameters;
  16858. };
  16859. /**
  16860. * Disables the feature FacetData and frees the related memory.
  16861. * Returns the AbstractMesh.
  16862. */
  16863. AbstractMesh.prototype.disableFacetData = function () {
  16864. if (this._facetDataEnabled) {
  16865. this._facetDataEnabled = false;
  16866. this._facetPositions = new Array();
  16867. this._facetNormals = new Array();
  16868. this._facetPartitioning = new Array();
  16869. this._facetParameters = null;
  16870. this._depthSortedIndices = new Uint32Array(0);
  16871. }
  16872. return this;
  16873. };
  16874. /**
  16875. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  16876. * Returns the mesh.
  16877. */
  16878. AbstractMesh.prototype.updateIndices = function (indices) {
  16879. return this;
  16880. };
  16881. /**
  16882. * The mesh Geometry. Actually used by the Mesh object.
  16883. * Returns a blank geometry object.
  16884. */
  16885. /**
  16886. * Creates new normals data for the mesh.
  16887. * @param updatable.
  16888. */
  16889. AbstractMesh.prototype.createNormals = function (updatable) {
  16890. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16891. var indices = this.getIndices();
  16892. var normals;
  16893. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16894. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16895. }
  16896. else {
  16897. normals = [];
  16898. }
  16899. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  16900. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  16901. };
  16902. /**
  16903. * Align the mesh with a normal.
  16904. * Returns the mesh.
  16905. */
  16906. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  16907. if (!upDirection) {
  16908. upDirection = BABYLON.Axis.Y;
  16909. }
  16910. var axisX = BABYLON.Tmp.Vector3[0];
  16911. var axisZ = BABYLON.Tmp.Vector3[1];
  16912. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  16913. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  16914. if (this.rotationQuaternion) {
  16915. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  16916. }
  16917. else {
  16918. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  16919. }
  16920. return this;
  16921. };
  16922. AbstractMesh.prototype.checkOcclusionQuery = function () {
  16923. var engine = this.getEngine();
  16924. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  16925. this._isOccluded = false;
  16926. return;
  16927. }
  16928. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  16929. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  16930. if (isOcclusionQueryAvailable) {
  16931. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  16932. this._isOcclusionQueryInProgress = false;
  16933. this._occlusionInternalRetryCounter = 0;
  16934. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  16935. }
  16936. else {
  16937. this._occlusionInternalRetryCounter++;
  16938. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  16939. this._isOcclusionQueryInProgress = false;
  16940. this._occlusionInternalRetryCounter = 0;
  16941. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  16942. // if strict continue the last state of the object.
  16943. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  16944. }
  16945. else {
  16946. return;
  16947. }
  16948. }
  16949. }
  16950. var scene = this.getScene();
  16951. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  16952. if (!this._occlusionQuery) {
  16953. this._occlusionQuery = engine.createQuery();
  16954. }
  16955. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  16956. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  16957. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  16958. this._isOcclusionQueryInProgress = true;
  16959. };
  16960. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  16961. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  16962. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  16963. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  16964. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  16965. return AbstractMesh;
  16966. }(BABYLON.TransformNode));
  16967. BABYLON.AbstractMesh = AbstractMesh;
  16968. })(BABYLON || (BABYLON = {}));
  16969. //# sourceMappingURL=babylon.abstractMesh.js.map
  16970. var BABYLON;
  16971. (function (BABYLON) {
  16972. var Light = /** @class */ (function (_super) {
  16973. __extends(Light, _super);
  16974. /**
  16975. * Creates a Light object in the scene.
  16976. * Documentation : http://doc.babylonjs.com/tutorials/lights
  16977. */
  16978. function Light(name, scene) {
  16979. var _this = _super.call(this, name, scene) || this;
  16980. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  16981. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  16982. _this.intensity = 1.0;
  16983. _this.range = Number.MAX_VALUE;
  16984. /**
  16985. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  16986. * of light.
  16987. */
  16988. _this._photometricScale = 1.0;
  16989. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  16990. _this._radius = 0.00001;
  16991. _this.renderPriority = 0;
  16992. /**
  16993. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  16994. * the current shadow generator.
  16995. */
  16996. _this.shadowEnabled = true;
  16997. _this._excludeWithLayerMask = 0;
  16998. _this._includeOnlyWithLayerMask = 0;
  16999. _this._lightmapMode = 0;
  17000. _this._excludedMeshesIds = new Array();
  17001. _this._includedOnlyMeshesIds = new Array();
  17002. _this.getScene().addLight(_this);
  17003. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17004. _this._buildUniformLayout();
  17005. _this.includedOnlyMeshes = new Array();
  17006. _this.excludedMeshes = new Array();
  17007. _this._resyncMeshes();
  17008. return _this;
  17009. }
  17010. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17011. /**
  17012. * If every light affecting the material is in this lightmapMode,
  17013. * material.lightmapTexture adds or multiplies
  17014. * (depends on material.useLightmapAsShadowmap)
  17015. * after every other light calculations.
  17016. */
  17017. get: function () {
  17018. return Light._LIGHTMAP_DEFAULT;
  17019. },
  17020. enumerable: true,
  17021. configurable: true
  17022. });
  17023. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17024. /**
  17025. * material.lightmapTexture as only diffuse lighting from this light
  17026. * adds only specular lighting from this light
  17027. * adds dynamic shadows
  17028. */
  17029. get: function () {
  17030. return Light._LIGHTMAP_SPECULAR;
  17031. },
  17032. enumerable: true,
  17033. configurable: true
  17034. });
  17035. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17036. /**
  17037. * material.lightmapTexture as only lighting
  17038. * no light calculation from this light
  17039. * only adds dynamic shadows from this light
  17040. */
  17041. get: function () {
  17042. return Light._LIGHTMAP_SHADOWSONLY;
  17043. },
  17044. enumerable: true,
  17045. configurable: true
  17046. });
  17047. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17048. /**
  17049. * Each light type uses the default quantity according to its type:
  17050. * point/spot lights use luminous intensity
  17051. * directional lights use illuminance
  17052. */
  17053. get: function () {
  17054. return Light._INTENSITYMODE_AUTOMATIC;
  17055. },
  17056. enumerable: true,
  17057. configurable: true
  17058. });
  17059. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17060. /**
  17061. * lumen (lm)
  17062. */
  17063. get: function () {
  17064. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17065. },
  17066. enumerable: true,
  17067. configurable: true
  17068. });
  17069. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17070. /**
  17071. * candela (lm/sr)
  17072. */
  17073. get: function () {
  17074. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17075. },
  17076. enumerable: true,
  17077. configurable: true
  17078. });
  17079. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17080. /**
  17081. * lux (lm/m^2)
  17082. */
  17083. get: function () {
  17084. return Light._INTENSITYMODE_ILLUMINANCE;
  17085. },
  17086. enumerable: true,
  17087. configurable: true
  17088. });
  17089. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17090. /**
  17091. * nit (cd/m^2)
  17092. */
  17093. get: function () {
  17094. return Light._INTENSITYMODE_LUMINANCE;
  17095. },
  17096. enumerable: true,
  17097. configurable: true
  17098. });
  17099. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17100. /**
  17101. * Light type const id of the point light.
  17102. */
  17103. get: function () {
  17104. return Light._LIGHTTYPEID_POINTLIGHT;
  17105. },
  17106. enumerable: true,
  17107. configurable: true
  17108. });
  17109. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17110. /**
  17111. * Light type const id of the directional light.
  17112. */
  17113. get: function () {
  17114. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17115. },
  17116. enumerable: true,
  17117. configurable: true
  17118. });
  17119. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17120. /**
  17121. * Light type const id of the spot light.
  17122. */
  17123. get: function () {
  17124. return Light._LIGHTTYPEID_SPOTLIGHT;
  17125. },
  17126. enumerable: true,
  17127. configurable: true
  17128. });
  17129. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17130. /**
  17131. * Light type const id of the hemispheric light.
  17132. */
  17133. get: function () {
  17134. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17135. },
  17136. enumerable: true,
  17137. configurable: true
  17138. });
  17139. Object.defineProperty(Light.prototype, "intensityMode", {
  17140. /**
  17141. * Gets the photometric scale used to interpret the intensity.
  17142. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17143. */
  17144. get: function () {
  17145. return this._intensityMode;
  17146. },
  17147. /**
  17148. * Sets the photometric scale used to interpret the intensity.
  17149. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17150. */
  17151. set: function (value) {
  17152. this._intensityMode = value;
  17153. this._computePhotometricScale();
  17154. },
  17155. enumerable: true,
  17156. configurable: true
  17157. });
  17158. ;
  17159. ;
  17160. Object.defineProperty(Light.prototype, "radius", {
  17161. /**
  17162. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17163. */
  17164. get: function () {
  17165. return this._radius;
  17166. },
  17167. /**
  17168. * sets the light radius used by PBR Materials to simulate soft area lights.
  17169. */
  17170. set: function (value) {
  17171. this._radius = value;
  17172. this._computePhotometricScale();
  17173. },
  17174. enumerable: true,
  17175. configurable: true
  17176. });
  17177. ;
  17178. ;
  17179. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17180. get: function () {
  17181. return this._includedOnlyMeshes;
  17182. },
  17183. set: function (value) {
  17184. this._includedOnlyMeshes = value;
  17185. this._hookArrayForIncludedOnly(value);
  17186. },
  17187. enumerable: true,
  17188. configurable: true
  17189. });
  17190. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17191. get: function () {
  17192. return this._excludedMeshes;
  17193. },
  17194. set: function (value) {
  17195. this._excludedMeshes = value;
  17196. this._hookArrayForExcluded(value);
  17197. },
  17198. enumerable: true,
  17199. configurable: true
  17200. });
  17201. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17202. get: function () {
  17203. return this._excludeWithLayerMask;
  17204. },
  17205. set: function (value) {
  17206. this._excludeWithLayerMask = value;
  17207. this._resyncMeshes();
  17208. },
  17209. enumerable: true,
  17210. configurable: true
  17211. });
  17212. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17213. get: function () {
  17214. return this._includeOnlyWithLayerMask;
  17215. },
  17216. set: function (value) {
  17217. this._includeOnlyWithLayerMask = value;
  17218. this._resyncMeshes();
  17219. },
  17220. enumerable: true,
  17221. configurable: true
  17222. });
  17223. Object.defineProperty(Light.prototype, "lightmapMode", {
  17224. get: function () {
  17225. return this._lightmapMode;
  17226. },
  17227. set: function (value) {
  17228. if (this._lightmapMode === value) {
  17229. return;
  17230. }
  17231. this._lightmapMode = value;
  17232. this._markMeshesAsLightDirty();
  17233. },
  17234. enumerable: true,
  17235. configurable: true
  17236. });
  17237. Light.prototype._buildUniformLayout = function () {
  17238. // Overridden
  17239. };
  17240. /**
  17241. * Returns the string "Light".
  17242. */
  17243. Light.prototype.getClassName = function () {
  17244. return "Light";
  17245. };
  17246. /**
  17247. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17248. */
  17249. Light.prototype.toString = function (fullDetails) {
  17250. var ret = "Name: " + this.name;
  17251. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17252. if (this.animations) {
  17253. for (var i = 0; i < this.animations.length; i++) {
  17254. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17255. }
  17256. }
  17257. if (fullDetails) {
  17258. }
  17259. return ret;
  17260. };
  17261. /**
  17262. * Set the enabled state of this node.
  17263. * @param {boolean} value - the new enabled state
  17264. * @see isEnabled
  17265. */
  17266. Light.prototype.setEnabled = function (value) {
  17267. _super.prototype.setEnabled.call(this, value);
  17268. this._resyncMeshes();
  17269. };
  17270. /**
  17271. * Returns the Light associated shadow generator.
  17272. */
  17273. Light.prototype.getShadowGenerator = function () {
  17274. return this._shadowGenerator;
  17275. };
  17276. /**
  17277. * Returns a Vector3, the absolute light position in the World.
  17278. */
  17279. Light.prototype.getAbsolutePosition = function () {
  17280. return BABYLON.Vector3.Zero();
  17281. };
  17282. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17283. };
  17284. Light.prototype._getWorldMatrix = function () {
  17285. return BABYLON.Matrix.Identity();
  17286. };
  17287. /**
  17288. * Boolean : True if the light will affect the passed mesh.
  17289. */
  17290. Light.prototype.canAffectMesh = function (mesh) {
  17291. if (!mesh) {
  17292. return true;
  17293. }
  17294. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17295. return false;
  17296. }
  17297. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17298. return false;
  17299. }
  17300. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17301. return false;
  17302. }
  17303. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17304. return false;
  17305. }
  17306. return true;
  17307. };
  17308. /**
  17309. * Returns the light World matrix.
  17310. */
  17311. Light.prototype.getWorldMatrix = function () {
  17312. this._currentRenderId = this.getScene().getRenderId();
  17313. var worldMatrix = this._getWorldMatrix();
  17314. if (this.parent && this.parent.getWorldMatrix) {
  17315. if (!this._parentedWorldMatrix) {
  17316. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17317. }
  17318. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17319. this._markSyncedWithParent();
  17320. return this._parentedWorldMatrix;
  17321. }
  17322. return worldMatrix;
  17323. };
  17324. /**
  17325. * Sort function to order lights for rendering.
  17326. * @param a First Light object to compare to second.
  17327. * @param b Second Light object to compare first.
  17328. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17329. */
  17330. Light.compareLightsPriority = function (a, b) {
  17331. //shadow-casting lights have priority over non-shadow-casting lights
  17332. //the renderPrioirty is a secondary sort criterion
  17333. if (a.shadowEnabled !== b.shadowEnabled) {
  17334. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17335. }
  17336. return b.renderPriority - a.renderPriority;
  17337. };
  17338. /**
  17339. * Disposes the light.
  17340. */
  17341. Light.prototype.dispose = function () {
  17342. if (this._shadowGenerator) {
  17343. this._shadowGenerator.dispose();
  17344. this._shadowGenerator = null;
  17345. }
  17346. // Animations
  17347. this.getScene().stopAnimation(this);
  17348. this._uniformBuffer.dispose();
  17349. // Remove from scene
  17350. this.getScene().removeLight(this);
  17351. _super.prototype.dispose.call(this);
  17352. };
  17353. /**
  17354. * Returns the light type ID (integer).
  17355. */
  17356. Light.prototype.getTypeID = function () {
  17357. return 0;
  17358. };
  17359. /**
  17360. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17361. */
  17362. Light.prototype.getScaledIntensity = function () {
  17363. return this._photometricScale * this.intensity;
  17364. };
  17365. /**
  17366. * Returns a new Light object, named "name", from the current one.
  17367. */
  17368. Light.prototype.clone = function (name) {
  17369. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17370. if (!constructor) {
  17371. return null;
  17372. }
  17373. return BABYLON.SerializationHelper.Clone(constructor, this);
  17374. };
  17375. /**
  17376. * Serializes the current light into a Serialization object.
  17377. * Returns the serialized object.
  17378. */
  17379. Light.prototype.serialize = function () {
  17380. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17381. // Type
  17382. serializationObject.type = this.getTypeID();
  17383. // Parent
  17384. if (this.parent) {
  17385. serializationObject.parentId = this.parent.id;
  17386. }
  17387. // Inclusion / exclusions
  17388. if (this.excludedMeshes.length > 0) {
  17389. serializationObject.excludedMeshesIds = [];
  17390. this.excludedMeshes.forEach(function (mesh) {
  17391. serializationObject.excludedMeshesIds.push(mesh.id);
  17392. });
  17393. }
  17394. if (this.includedOnlyMeshes.length > 0) {
  17395. serializationObject.includedOnlyMeshesIds = [];
  17396. this.includedOnlyMeshes.forEach(function (mesh) {
  17397. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17398. });
  17399. }
  17400. // Animations
  17401. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17402. serializationObject.ranges = this.serializeAnimationRanges();
  17403. return serializationObject;
  17404. };
  17405. /**
  17406. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  17407. * This new light is named "name" and added to the passed scene.
  17408. */
  17409. Light.GetConstructorFromName = function (type, name, scene) {
  17410. switch (type) {
  17411. case 0:
  17412. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  17413. case 1:
  17414. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  17415. case 2:
  17416. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  17417. case 3:
  17418. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  17419. }
  17420. return null;
  17421. };
  17422. /**
  17423. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  17424. */
  17425. Light.Parse = function (parsedLight, scene) {
  17426. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  17427. if (!constructor) {
  17428. return null;
  17429. }
  17430. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  17431. // Inclusion / exclusions
  17432. if (parsedLight.excludedMeshesIds) {
  17433. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17434. }
  17435. if (parsedLight.includedOnlyMeshesIds) {
  17436. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17437. }
  17438. // Parent
  17439. if (parsedLight.parentId) {
  17440. light._waitingParentId = parsedLight.parentId;
  17441. }
  17442. // Animations
  17443. if (parsedLight.animations) {
  17444. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17445. var parsedAnimation = parsedLight.animations[animationIndex];
  17446. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17447. }
  17448. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  17449. }
  17450. if (parsedLight.autoAnimate) {
  17451. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  17452. }
  17453. return light;
  17454. };
  17455. Light.prototype._hookArrayForExcluded = function (array) {
  17456. var _this = this;
  17457. var oldPush = array.push;
  17458. array.push = function () {
  17459. var items = [];
  17460. for (var _i = 0; _i < arguments.length; _i++) {
  17461. items[_i] = arguments[_i];
  17462. }
  17463. var result = oldPush.apply(array, items);
  17464. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  17465. var item = items_1[_a];
  17466. item._resyncLighSource(_this);
  17467. }
  17468. return result;
  17469. };
  17470. var oldSplice = array.splice;
  17471. array.splice = function (index, deleteCount) {
  17472. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17473. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  17474. var item = deleted_1[_i];
  17475. item._resyncLighSource(_this);
  17476. }
  17477. return deleted;
  17478. };
  17479. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  17480. var item = array_1[_i];
  17481. item._resyncLighSource(this);
  17482. }
  17483. };
  17484. Light.prototype._hookArrayForIncludedOnly = function (array) {
  17485. var _this = this;
  17486. var oldPush = array.push;
  17487. array.push = function () {
  17488. var items = [];
  17489. for (var _i = 0; _i < arguments.length; _i++) {
  17490. items[_i] = arguments[_i];
  17491. }
  17492. var result = oldPush.apply(array, items);
  17493. _this._resyncMeshes();
  17494. return result;
  17495. };
  17496. var oldSplice = array.splice;
  17497. array.splice = function (index, deleteCount) {
  17498. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17499. _this._resyncMeshes();
  17500. return deleted;
  17501. };
  17502. this._resyncMeshes();
  17503. };
  17504. Light.prototype._resyncMeshes = function () {
  17505. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17506. var mesh = _a[_i];
  17507. mesh._resyncLighSource(this);
  17508. }
  17509. };
  17510. Light.prototype._markMeshesAsLightDirty = function () {
  17511. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17512. var mesh = _a[_i];
  17513. if (mesh._lightSources.indexOf(this) !== -1) {
  17514. mesh._markSubMeshesAsLightDirty();
  17515. }
  17516. }
  17517. };
  17518. /**
  17519. * Recomputes the cached photometric scale if needed.
  17520. */
  17521. Light.prototype._computePhotometricScale = function () {
  17522. this._photometricScale = this._getPhotometricScale();
  17523. this.getScene().resetCachedMaterial();
  17524. };
  17525. /**
  17526. * Returns the Photometric Scale according to the light type and intensity mode.
  17527. */
  17528. Light.prototype._getPhotometricScale = function () {
  17529. var photometricScale = 0.0;
  17530. var lightTypeID = this.getTypeID();
  17531. //get photometric mode
  17532. var photometricMode = this.intensityMode;
  17533. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  17534. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  17535. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  17536. }
  17537. else {
  17538. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  17539. }
  17540. }
  17541. //compute photometric scale
  17542. switch (lightTypeID) {
  17543. case Light.LIGHTTYPEID_POINTLIGHT:
  17544. case Light.LIGHTTYPEID_SPOTLIGHT:
  17545. switch (photometricMode) {
  17546. case Light.INTENSITYMODE_LUMINOUSPOWER:
  17547. photometricScale = 1.0 / (4.0 * Math.PI);
  17548. break;
  17549. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  17550. photometricScale = 1.0;
  17551. break;
  17552. case Light.INTENSITYMODE_LUMINANCE:
  17553. photometricScale = this.radius * this.radius;
  17554. break;
  17555. }
  17556. break;
  17557. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  17558. switch (photometricMode) {
  17559. case Light.INTENSITYMODE_ILLUMINANCE:
  17560. photometricScale = 1.0;
  17561. break;
  17562. case Light.INTENSITYMODE_LUMINANCE:
  17563. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  17564. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  17565. var apexAngleRadians = this.radius;
  17566. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  17567. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  17568. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  17569. photometricScale = solidAngle;
  17570. break;
  17571. }
  17572. break;
  17573. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  17574. // No fall off in hemisperic light.
  17575. photometricScale = 1.0;
  17576. break;
  17577. }
  17578. return photometricScale;
  17579. };
  17580. Light.prototype._reorderLightsInScene = function () {
  17581. var scene = this.getScene();
  17582. if (this._renderPriority != 0) {
  17583. scene.requireLightSorting = true;
  17584. }
  17585. this.getScene().sortLightsByPriority();
  17586. };
  17587. //lightmapMode Consts
  17588. Light._LIGHTMAP_DEFAULT = 0;
  17589. Light._LIGHTMAP_SPECULAR = 1;
  17590. Light._LIGHTMAP_SHADOWSONLY = 2;
  17591. // Intensity Mode Consts
  17592. Light._INTENSITYMODE_AUTOMATIC = 0;
  17593. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  17594. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  17595. Light._INTENSITYMODE_ILLUMINANCE = 3;
  17596. Light._INTENSITYMODE_LUMINANCE = 4;
  17597. // Light types ids const.
  17598. Light._LIGHTTYPEID_POINTLIGHT = 0;
  17599. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  17600. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  17601. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  17602. __decorate([
  17603. BABYLON.serializeAsColor3()
  17604. ], Light.prototype, "diffuse", void 0);
  17605. __decorate([
  17606. BABYLON.serializeAsColor3()
  17607. ], Light.prototype, "specular", void 0);
  17608. __decorate([
  17609. BABYLON.serialize()
  17610. ], Light.prototype, "intensity", void 0);
  17611. __decorate([
  17612. BABYLON.serialize()
  17613. ], Light.prototype, "range", void 0);
  17614. __decorate([
  17615. BABYLON.serialize()
  17616. ], Light.prototype, "intensityMode", null);
  17617. __decorate([
  17618. BABYLON.serialize()
  17619. ], Light.prototype, "radius", null);
  17620. __decorate([
  17621. BABYLON.serialize()
  17622. ], Light.prototype, "_renderPriority", void 0);
  17623. __decorate([
  17624. BABYLON.expandToProperty("_reorderLightsInScene")
  17625. ], Light.prototype, "renderPriority", void 0);
  17626. __decorate([
  17627. BABYLON.serialize()
  17628. ], Light.prototype, "shadowEnabled", void 0);
  17629. __decorate([
  17630. BABYLON.serialize("excludeWithLayerMask")
  17631. ], Light.prototype, "_excludeWithLayerMask", void 0);
  17632. __decorate([
  17633. BABYLON.serialize("includeOnlyWithLayerMask")
  17634. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  17635. __decorate([
  17636. BABYLON.serialize("lightmapMode")
  17637. ], Light.prototype, "_lightmapMode", void 0);
  17638. return Light;
  17639. }(BABYLON.Node));
  17640. BABYLON.Light = Light;
  17641. })(BABYLON || (BABYLON = {}));
  17642. //# sourceMappingURL=babylon.light.js.map
  17643. var BABYLON;
  17644. (function (BABYLON) {
  17645. var Camera = /** @class */ (function (_super) {
  17646. __extends(Camera, _super);
  17647. function Camera(name, position, scene) {
  17648. var _this = _super.call(this, name, scene) || this;
  17649. _this.upVector = BABYLON.Vector3.Up();
  17650. _this.orthoLeft = null;
  17651. _this.orthoRight = null;
  17652. _this.orthoBottom = null;
  17653. _this.orthoTop = null;
  17654. /**
  17655. * default : 0.8
  17656. * FOV is set in Radians.
  17657. */
  17658. _this.fov = 0.8;
  17659. _this.minZ = 1;
  17660. _this.maxZ = 10000.0;
  17661. _this.inertia = 0.9;
  17662. _this.mode = Camera.PERSPECTIVE_CAMERA;
  17663. _this.isIntermediate = false;
  17664. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  17665. /**
  17666. * Restricts the camera to viewing objects with the same layerMask.
  17667. * A camera with a layerMask of 1 will render meshes with no layerMask and meshes with a layerMask of 1.
  17668. */
  17669. _this.layerMask = 0x0FFFFFFF;
  17670. /**
  17671. * default : FOVMODE_VERTICAL_FIXED
  17672. * fovMode sets the camera frustum bounds to the viewport bounds.
  17673. */
  17674. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  17675. // Camera rig members
  17676. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  17677. _this._rigCameras = new Array();
  17678. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  17679. _this._skipRendering = false;
  17680. _this.customRenderTargets = new Array();
  17681. // Observables
  17682. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  17683. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  17684. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  17685. _this.onRestoreStateObservable = new BABYLON.Observable();
  17686. // Cache
  17687. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  17688. _this._projectionMatrix = new BABYLON.Matrix();
  17689. _this._doNotComputeProjectionMatrix = false;
  17690. _this._postProcesses = new Array();
  17691. _this._transformMatrix = BABYLON.Matrix.Zero();
  17692. _this._activeMeshes = new BABYLON.SmartArray(256);
  17693. _this._globalPosition = BABYLON.Vector3.Zero();
  17694. _this._refreshFrustumPlanes = true;
  17695. _this.getScene().addCamera(_this);
  17696. if (!_this.getScene().activeCamera) {
  17697. _this.getScene().activeCamera = _this;
  17698. }
  17699. _this.position = position;
  17700. return _this;
  17701. }
  17702. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  17703. get: function () {
  17704. return Camera._PERSPECTIVE_CAMERA;
  17705. },
  17706. enumerable: true,
  17707. configurable: true
  17708. });
  17709. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  17710. get: function () {
  17711. return Camera._ORTHOGRAPHIC_CAMERA;
  17712. },
  17713. enumerable: true,
  17714. configurable: true
  17715. });
  17716. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  17717. /**
  17718. * This is the default FOV mode for perspective cameras.
  17719. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  17720. *
  17721. */
  17722. get: function () {
  17723. return Camera._FOVMODE_VERTICAL_FIXED;
  17724. },
  17725. enumerable: true,
  17726. configurable: true
  17727. });
  17728. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  17729. /**
  17730. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  17731. *
  17732. */
  17733. get: function () {
  17734. return Camera._FOVMODE_HORIZONTAL_FIXED;
  17735. },
  17736. enumerable: true,
  17737. configurable: true
  17738. });
  17739. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  17740. get: function () {
  17741. return Camera._RIG_MODE_NONE;
  17742. },
  17743. enumerable: true,
  17744. configurable: true
  17745. });
  17746. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  17747. get: function () {
  17748. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  17749. },
  17750. enumerable: true,
  17751. configurable: true
  17752. });
  17753. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  17754. get: function () {
  17755. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  17756. },
  17757. enumerable: true,
  17758. configurable: true
  17759. });
  17760. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  17761. get: function () {
  17762. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17763. },
  17764. enumerable: true,
  17765. configurable: true
  17766. });
  17767. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  17768. get: function () {
  17769. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  17770. },
  17771. enumerable: true,
  17772. configurable: true
  17773. });
  17774. Object.defineProperty(Camera, "RIG_MODE_VR", {
  17775. get: function () {
  17776. return Camera._RIG_MODE_VR;
  17777. },
  17778. enumerable: true,
  17779. configurable: true
  17780. });
  17781. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  17782. get: function () {
  17783. return Camera._RIG_MODE_WEBVR;
  17784. },
  17785. enumerable: true,
  17786. configurable: true
  17787. });
  17788. /**
  17789. * Store current camera state (fov, position, etc..)
  17790. */
  17791. Camera.prototype.storeState = function () {
  17792. this._stateStored = true;
  17793. this._storedFov = this.fov;
  17794. return this;
  17795. };
  17796. /**
  17797. * Restores the camera state values if it has been stored. You must call storeState() first
  17798. */
  17799. Camera.prototype._restoreStateValues = function () {
  17800. if (!this._stateStored) {
  17801. return false;
  17802. }
  17803. this.fov = this._storedFov;
  17804. return true;
  17805. };
  17806. /**
  17807. * Restored camera state. You must call storeState() first
  17808. */
  17809. Camera.prototype.restoreState = function () {
  17810. if (this._restoreStateValues()) {
  17811. this.onRestoreStateObservable.notifyObservers(this);
  17812. return true;
  17813. }
  17814. return false;
  17815. };
  17816. Camera.prototype.getClassName = function () {
  17817. return "Camera";
  17818. };
  17819. /**
  17820. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17821. */
  17822. Camera.prototype.toString = function (fullDetails) {
  17823. var ret = "Name: " + this.name;
  17824. ret += ", type: " + this.getClassName();
  17825. if (this.animations) {
  17826. for (var i = 0; i < this.animations.length; i++) {
  17827. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17828. }
  17829. }
  17830. if (fullDetails) {
  17831. }
  17832. return ret;
  17833. };
  17834. Object.defineProperty(Camera.prototype, "globalPosition", {
  17835. get: function () {
  17836. return this._globalPosition;
  17837. },
  17838. enumerable: true,
  17839. configurable: true
  17840. });
  17841. Camera.prototype.getActiveMeshes = function () {
  17842. return this._activeMeshes;
  17843. };
  17844. Camera.prototype.isActiveMesh = function (mesh) {
  17845. return (this._activeMeshes.indexOf(mesh) !== -1);
  17846. };
  17847. //Cache
  17848. Camera.prototype._initCache = function () {
  17849. _super.prototype._initCache.call(this);
  17850. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17851. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17852. this._cache.mode = undefined;
  17853. this._cache.minZ = undefined;
  17854. this._cache.maxZ = undefined;
  17855. this._cache.fov = undefined;
  17856. this._cache.fovMode = undefined;
  17857. this._cache.aspectRatio = undefined;
  17858. this._cache.orthoLeft = undefined;
  17859. this._cache.orthoRight = undefined;
  17860. this._cache.orthoBottom = undefined;
  17861. this._cache.orthoTop = undefined;
  17862. this._cache.renderWidth = undefined;
  17863. this._cache.renderHeight = undefined;
  17864. };
  17865. Camera.prototype._updateCache = function (ignoreParentClass) {
  17866. if (!ignoreParentClass) {
  17867. _super.prototype._updateCache.call(this);
  17868. }
  17869. this._cache.position.copyFrom(this.position);
  17870. this._cache.upVector.copyFrom(this.upVector);
  17871. };
  17872. // Synchronized
  17873. Camera.prototype._isSynchronized = function () {
  17874. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  17875. };
  17876. Camera.prototype._isSynchronizedViewMatrix = function () {
  17877. if (!_super.prototype._isSynchronized.call(this))
  17878. return false;
  17879. return this._cache.position.equals(this.position)
  17880. && this._cache.upVector.equals(this.upVector)
  17881. && this.isSynchronizedWithParent();
  17882. };
  17883. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  17884. var check = this._cache.mode === this.mode
  17885. && this._cache.minZ === this.minZ
  17886. && this._cache.maxZ === this.maxZ;
  17887. if (!check) {
  17888. return false;
  17889. }
  17890. var engine = this.getEngine();
  17891. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  17892. check = this._cache.fov === this.fov
  17893. && this._cache.fovMode === this.fovMode
  17894. && this._cache.aspectRatio === engine.getAspectRatio(this);
  17895. }
  17896. else {
  17897. check = this._cache.orthoLeft === this.orthoLeft
  17898. && this._cache.orthoRight === this.orthoRight
  17899. && this._cache.orthoBottom === this.orthoBottom
  17900. && this._cache.orthoTop === this.orthoTop
  17901. && this._cache.renderWidth === engine.getRenderWidth()
  17902. && this._cache.renderHeight === engine.getRenderHeight();
  17903. }
  17904. return check;
  17905. };
  17906. // Controls
  17907. Camera.prototype.attachControl = function (element, noPreventDefault) {
  17908. };
  17909. Camera.prototype.detachControl = function (element) {
  17910. };
  17911. Camera.prototype.update = function () {
  17912. this._checkInputs();
  17913. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17914. this._updateRigCameras();
  17915. }
  17916. };
  17917. Camera.prototype._checkInputs = function () {
  17918. this.onAfterCheckInputsObservable.notifyObservers(this);
  17919. };
  17920. Object.defineProperty(Camera.prototype, "rigCameras", {
  17921. get: function () {
  17922. return this._rigCameras;
  17923. },
  17924. enumerable: true,
  17925. configurable: true
  17926. });
  17927. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  17928. get: function () {
  17929. return this._rigPostProcess;
  17930. },
  17931. enumerable: true,
  17932. configurable: true
  17933. });
  17934. Camera.prototype._cascadePostProcessesToRigCams = function () {
  17935. // invalidate framebuffer
  17936. if (this._postProcesses.length > 0) {
  17937. this._postProcesses[0].markTextureDirty();
  17938. }
  17939. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  17940. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  17941. var cam = this._rigCameras[i];
  17942. var rigPostProcess = cam._rigPostProcess;
  17943. // for VR rig, there does not have to be a post process
  17944. if (rigPostProcess) {
  17945. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  17946. if (isPass) {
  17947. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  17948. cam.isIntermediate = this._postProcesses.length === 0;
  17949. }
  17950. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  17951. rigPostProcess.markTextureDirty();
  17952. }
  17953. else {
  17954. cam._postProcesses = this._postProcesses.slice(0);
  17955. }
  17956. }
  17957. };
  17958. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  17959. if (insertAt === void 0) { insertAt = null; }
  17960. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  17961. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  17962. return 0;
  17963. }
  17964. if (insertAt == null || insertAt < 0) {
  17965. this._postProcesses.push(postProcess);
  17966. }
  17967. else {
  17968. this._postProcesses.splice(insertAt, 0, postProcess);
  17969. }
  17970. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17971. return this._postProcesses.indexOf(postProcess);
  17972. };
  17973. Camera.prototype.detachPostProcess = function (postProcess) {
  17974. var idx = this._postProcesses.indexOf(postProcess);
  17975. if (idx !== -1) {
  17976. this._postProcesses.splice(idx, 1);
  17977. }
  17978. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17979. };
  17980. Camera.prototype.getWorldMatrix = function () {
  17981. if (!this._worldMatrix) {
  17982. this._worldMatrix = BABYLON.Matrix.Identity();
  17983. }
  17984. var viewMatrix = this.getViewMatrix();
  17985. viewMatrix.invertToRef(this._worldMatrix);
  17986. return this._worldMatrix;
  17987. };
  17988. Camera.prototype._getViewMatrix = function () {
  17989. return BABYLON.Matrix.Identity();
  17990. };
  17991. Camera.prototype.getViewMatrix = function (force) {
  17992. if (!force && this._isSynchronizedViewMatrix()) {
  17993. return this._computedViewMatrix;
  17994. }
  17995. this.updateCache();
  17996. this._computedViewMatrix = this._getViewMatrix();
  17997. this._currentRenderId = this.getScene().getRenderId();
  17998. this._refreshFrustumPlanes = true;
  17999. if (!this.parent || !this.parent.getWorldMatrix) {
  18000. this._globalPosition.copyFrom(this.position);
  18001. }
  18002. else {
  18003. if (!this._worldMatrix) {
  18004. this._worldMatrix = BABYLON.Matrix.Identity();
  18005. }
  18006. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18007. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18008. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18009. this._computedViewMatrix.invert();
  18010. this._markSyncedWithParent();
  18011. }
  18012. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18013. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18014. }
  18015. this.onViewMatrixChangedObservable.notifyObservers(this);
  18016. return this._computedViewMatrix;
  18017. };
  18018. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18019. this._doNotComputeProjectionMatrix = true;
  18020. if (projection !== undefined) {
  18021. this._projectionMatrix = projection;
  18022. }
  18023. };
  18024. ;
  18025. Camera.prototype.unfreezeProjectionMatrix = function () {
  18026. this._doNotComputeProjectionMatrix = false;
  18027. };
  18028. ;
  18029. Camera.prototype.getProjectionMatrix = function (force) {
  18030. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18031. return this._projectionMatrix;
  18032. }
  18033. // Cache
  18034. this._cache.mode = this.mode;
  18035. this._cache.minZ = this.minZ;
  18036. this._cache.maxZ = this.maxZ;
  18037. // Matrix
  18038. this._refreshFrustumPlanes = true;
  18039. var engine = this.getEngine();
  18040. var scene = this.getScene();
  18041. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18042. this._cache.fov = this.fov;
  18043. this._cache.fovMode = this.fovMode;
  18044. this._cache.aspectRatio = engine.getAspectRatio(this);
  18045. if (this.minZ <= 0) {
  18046. this.minZ = 0.1;
  18047. }
  18048. if (scene.useRightHandedSystem) {
  18049. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18050. }
  18051. else {
  18052. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18053. }
  18054. }
  18055. else {
  18056. var halfWidth = engine.getRenderWidth() / 2.0;
  18057. var halfHeight = engine.getRenderHeight() / 2.0;
  18058. if (scene.useRightHandedSystem) {
  18059. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18060. }
  18061. else {
  18062. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18063. }
  18064. this._cache.orthoLeft = this.orthoLeft;
  18065. this._cache.orthoRight = this.orthoRight;
  18066. this._cache.orthoBottom = this.orthoBottom;
  18067. this._cache.orthoTop = this.orthoTop;
  18068. this._cache.renderWidth = engine.getRenderWidth();
  18069. this._cache.renderHeight = engine.getRenderHeight();
  18070. }
  18071. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18072. return this._projectionMatrix;
  18073. };
  18074. Camera.prototype.getTranformationMatrix = function () {
  18075. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18076. return this._transformMatrix;
  18077. };
  18078. Camera.prototype.updateFrustumPlanes = function () {
  18079. if (!this._refreshFrustumPlanes) {
  18080. return;
  18081. }
  18082. this.getTranformationMatrix();
  18083. if (!this._frustumPlanes) {
  18084. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18085. }
  18086. else {
  18087. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18088. }
  18089. this._refreshFrustumPlanes = false;
  18090. };
  18091. Camera.prototype.isInFrustum = function (target) {
  18092. this.updateFrustumPlanes();
  18093. return target.isInFrustum(this._frustumPlanes);
  18094. };
  18095. Camera.prototype.isCompletelyInFrustum = function (target) {
  18096. this.updateFrustumPlanes();
  18097. return target.isCompletelyInFrustum(this._frustumPlanes);
  18098. };
  18099. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18100. if (length === void 0) { length = 100; }
  18101. if (!transform) {
  18102. transform = this.getWorldMatrix();
  18103. }
  18104. if (!origin) {
  18105. origin = this.position;
  18106. }
  18107. var forward = new BABYLON.Vector3(0, 0, 1);
  18108. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18109. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18110. return new BABYLON.Ray(origin, direction, length);
  18111. };
  18112. Camera.prototype.dispose = function () {
  18113. // Observables
  18114. this.onViewMatrixChangedObservable.clear();
  18115. this.onProjectionMatrixChangedObservable.clear();
  18116. this.onAfterCheckInputsObservable.clear();
  18117. this.onRestoreStateObservable.clear();
  18118. // Inputs
  18119. if (this.inputs) {
  18120. this.inputs.clear();
  18121. }
  18122. // Animations
  18123. this.getScene().stopAnimation(this);
  18124. // Remove from scene
  18125. this.getScene().removeCamera(this);
  18126. while (this._rigCameras.length > 0) {
  18127. var camera = this._rigCameras.pop();
  18128. if (camera) {
  18129. camera.dispose();
  18130. }
  18131. }
  18132. // Postprocesses
  18133. if (this._rigPostProcess) {
  18134. this._rigPostProcess.dispose(this);
  18135. this._rigPostProcess = null;
  18136. this._postProcesses = [];
  18137. }
  18138. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18139. this._rigPostProcess = null;
  18140. this._postProcesses = [];
  18141. }
  18142. else {
  18143. var i = this._postProcesses.length;
  18144. while (--i >= 0) {
  18145. this._postProcesses[i].dispose(this);
  18146. }
  18147. }
  18148. // Render targets
  18149. var i = this.customRenderTargets.length;
  18150. while (--i >= 0) {
  18151. this.customRenderTargets[i].dispose();
  18152. }
  18153. this.customRenderTargets = [];
  18154. // Active Meshes
  18155. this._activeMeshes.dispose();
  18156. _super.prototype.dispose.call(this);
  18157. };
  18158. Object.defineProperty(Camera.prototype, "leftCamera", {
  18159. // ---- Camera rigs section ----
  18160. get: function () {
  18161. if (this._rigCameras.length < 1) {
  18162. return null;
  18163. }
  18164. return this._rigCameras[0];
  18165. },
  18166. enumerable: true,
  18167. configurable: true
  18168. });
  18169. Object.defineProperty(Camera.prototype, "rightCamera", {
  18170. get: function () {
  18171. if (this._rigCameras.length < 2) {
  18172. return null;
  18173. }
  18174. return this._rigCameras[1];
  18175. },
  18176. enumerable: true,
  18177. configurable: true
  18178. });
  18179. Camera.prototype.getLeftTarget = function () {
  18180. if (this._rigCameras.length < 1) {
  18181. return null;
  18182. }
  18183. return this._rigCameras[0].getTarget();
  18184. };
  18185. Camera.prototype.getRightTarget = function () {
  18186. if (this._rigCameras.length < 2) {
  18187. return null;
  18188. }
  18189. return this._rigCameras[1].getTarget();
  18190. };
  18191. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18192. if (this.cameraRigMode === mode) {
  18193. return;
  18194. }
  18195. while (this._rigCameras.length > 0) {
  18196. var camera = this._rigCameras.pop();
  18197. if (camera) {
  18198. camera.dispose();
  18199. }
  18200. }
  18201. this.cameraRigMode = mode;
  18202. this._cameraRigParams = {};
  18203. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18204. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18205. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18206. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18207. // create the rig cameras, unless none
  18208. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18209. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18210. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18211. if (leftCamera && rightCamera) {
  18212. this._rigCameras.push(leftCamera);
  18213. this._rigCameras.push(rightCamera);
  18214. }
  18215. }
  18216. switch (this.cameraRigMode) {
  18217. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18218. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18219. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18220. break;
  18221. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18222. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18223. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18224. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18225. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18226. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18227. break;
  18228. case Camera.RIG_MODE_VR:
  18229. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18230. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18231. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18232. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18233. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18234. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18235. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18236. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18237. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18238. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18239. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18240. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18241. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18242. if (metrics.compensateDistortion) {
  18243. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18244. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18245. }
  18246. break;
  18247. case Camera.RIG_MODE_WEBVR:
  18248. if (rigParams.vrDisplay) {
  18249. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18250. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18251. //Left eye
  18252. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18253. this._rigCameras[0].setCameraRigParameter("left", true);
  18254. //leaving this for future reference
  18255. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18256. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18257. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18258. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18259. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18260. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18261. this._rigCameras[0].parent = this;
  18262. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18263. //Right eye
  18264. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18265. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18266. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18267. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18268. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18269. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18270. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18271. this._rigCameras[1].parent = this;
  18272. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18273. if (Camera.UseAlternateWebVRRendering) {
  18274. this._rigCameras[1]._skipRendering = true;
  18275. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18276. }
  18277. }
  18278. break;
  18279. }
  18280. this._cascadePostProcessesToRigCams();
  18281. this.update();
  18282. };
  18283. Camera.prototype._getVRProjectionMatrix = function () {
  18284. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18285. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18286. return this._projectionMatrix;
  18287. };
  18288. Camera.prototype._updateCameraRotationMatrix = function () {
  18289. //Here for WebVR
  18290. };
  18291. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18292. //Here for WebVR
  18293. };
  18294. /**
  18295. * This function MUST be overwritten by the different WebVR cameras available.
  18296. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18297. */
  18298. Camera.prototype._getWebVRProjectionMatrix = function () {
  18299. return BABYLON.Matrix.Identity();
  18300. };
  18301. /**
  18302. * This function MUST be overwritten by the different WebVR cameras available.
  18303. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18304. */
  18305. Camera.prototype._getWebVRViewMatrix = function () {
  18306. return BABYLON.Matrix.Identity();
  18307. };
  18308. Camera.prototype.setCameraRigParameter = function (name, value) {
  18309. if (!this._cameraRigParams) {
  18310. this._cameraRigParams = {};
  18311. }
  18312. this._cameraRigParams[name] = value;
  18313. //provisionnally:
  18314. if (name === "interaxialDistance") {
  18315. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18316. }
  18317. };
  18318. /**
  18319. * needs to be overridden by children so sub has required properties to be copied
  18320. */
  18321. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18322. return null;
  18323. };
  18324. /**
  18325. * May need to be overridden by children
  18326. */
  18327. Camera.prototype._updateRigCameras = function () {
  18328. for (var i = 0; i < this._rigCameras.length; i++) {
  18329. this._rigCameras[i].minZ = this.minZ;
  18330. this._rigCameras[i].maxZ = this.maxZ;
  18331. this._rigCameras[i].fov = this.fov;
  18332. }
  18333. // only update viewport when ANAGLYPH
  18334. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18335. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18336. }
  18337. };
  18338. Camera.prototype._setupInputs = function () {
  18339. };
  18340. Camera.prototype.serialize = function () {
  18341. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18342. // Type
  18343. serializationObject.type = this.getClassName();
  18344. // Parent
  18345. if (this.parent) {
  18346. serializationObject.parentId = this.parent.id;
  18347. }
  18348. if (this.inputs) {
  18349. this.inputs.serialize(serializationObject);
  18350. }
  18351. // Animations
  18352. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18353. serializationObject.ranges = this.serializeAnimationRanges();
  18354. return serializationObject;
  18355. };
  18356. Camera.prototype.clone = function (name) {
  18357. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18358. };
  18359. Camera.prototype.getDirection = function (localAxis) {
  18360. var result = BABYLON.Vector3.Zero();
  18361. this.getDirectionToRef(localAxis, result);
  18362. return result;
  18363. };
  18364. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18365. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18366. };
  18367. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18368. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18369. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18370. switch (type) {
  18371. case "ArcRotateCamera":
  18372. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18373. case "DeviceOrientationCamera":
  18374. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18375. case "FollowCamera":
  18376. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18377. case "ArcFollowCamera":
  18378. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18379. case "GamepadCamera":
  18380. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18381. case "TouchCamera":
  18382. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18383. case "VirtualJoysticksCamera":
  18384. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18385. case "WebVRFreeCamera":
  18386. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18387. case "WebVRGamepadCamera":
  18388. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18389. case "VRDeviceOrientationFreeCamera":
  18390. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18391. case "VRDeviceOrientationGamepadCamera":
  18392. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18393. case "AnaglyphArcRotateCamera":
  18394. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18395. case "AnaglyphFreeCamera":
  18396. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18397. case "AnaglyphGamepadCamera":
  18398. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18399. case "AnaglyphUniversalCamera":
  18400. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18401. case "StereoscopicArcRotateCamera":
  18402. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18403. case "StereoscopicFreeCamera":
  18404. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18405. case "StereoscopicGamepadCamera":
  18406. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18407. case "StereoscopicUniversalCamera":
  18408. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18409. case "FreeCamera":// Forcing Universal here
  18410. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18411. default:// Universal Camera is the default value
  18412. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18413. }
  18414. };
  18415. Camera.prototype.computeWorldMatrix = function () {
  18416. return this.getWorldMatrix();
  18417. };
  18418. Camera.Parse = function (parsedCamera, scene) {
  18419. var type = parsedCamera.type;
  18420. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  18421. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  18422. // Parent
  18423. if (parsedCamera.parentId) {
  18424. camera._waitingParentId = parsedCamera.parentId;
  18425. }
  18426. //If camera has an input manager, let it parse inputs settings
  18427. if (camera.inputs) {
  18428. camera.inputs.parse(parsedCamera);
  18429. camera._setupInputs();
  18430. }
  18431. if (camera.setPosition) {
  18432. camera.position.copyFromFloats(0, 0, 0);
  18433. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  18434. }
  18435. // Target
  18436. if (parsedCamera.target) {
  18437. if (camera.setTarget) {
  18438. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18439. }
  18440. }
  18441. // Apply 3d rig, when found
  18442. if (parsedCamera.cameraRigMode) {
  18443. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  18444. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  18445. }
  18446. // Animations
  18447. if (parsedCamera.animations) {
  18448. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18449. var parsedAnimation = parsedCamera.animations[animationIndex];
  18450. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18451. }
  18452. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  18453. }
  18454. if (parsedCamera.autoAnimate) {
  18455. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  18456. }
  18457. return camera;
  18458. };
  18459. // Statics
  18460. Camera._PERSPECTIVE_CAMERA = 0;
  18461. Camera._ORTHOGRAPHIC_CAMERA = 1;
  18462. Camera._FOVMODE_VERTICAL_FIXED = 0;
  18463. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  18464. Camera._RIG_MODE_NONE = 0;
  18465. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  18466. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  18467. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  18468. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  18469. Camera._RIG_MODE_VR = 20;
  18470. Camera._RIG_MODE_WEBVR = 21;
  18471. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  18472. Camera.UseAlternateWebVRRendering = false;
  18473. __decorate([
  18474. BABYLON.serializeAsVector3()
  18475. ], Camera.prototype, "position", void 0);
  18476. __decorate([
  18477. BABYLON.serializeAsVector3()
  18478. ], Camera.prototype, "upVector", void 0);
  18479. __decorate([
  18480. BABYLON.serialize()
  18481. ], Camera.prototype, "orthoLeft", void 0);
  18482. __decorate([
  18483. BABYLON.serialize()
  18484. ], Camera.prototype, "orthoRight", void 0);
  18485. __decorate([
  18486. BABYLON.serialize()
  18487. ], Camera.prototype, "orthoBottom", void 0);
  18488. __decorate([
  18489. BABYLON.serialize()
  18490. ], Camera.prototype, "orthoTop", void 0);
  18491. __decorate([
  18492. BABYLON.serialize()
  18493. ], Camera.prototype, "fov", void 0);
  18494. __decorate([
  18495. BABYLON.serialize()
  18496. ], Camera.prototype, "minZ", void 0);
  18497. __decorate([
  18498. BABYLON.serialize()
  18499. ], Camera.prototype, "maxZ", void 0);
  18500. __decorate([
  18501. BABYLON.serialize()
  18502. ], Camera.prototype, "inertia", void 0);
  18503. __decorate([
  18504. BABYLON.serialize()
  18505. ], Camera.prototype, "mode", void 0);
  18506. __decorate([
  18507. BABYLON.serialize()
  18508. ], Camera.prototype, "layerMask", void 0);
  18509. __decorate([
  18510. BABYLON.serialize()
  18511. ], Camera.prototype, "fovMode", void 0);
  18512. __decorate([
  18513. BABYLON.serialize()
  18514. ], Camera.prototype, "cameraRigMode", void 0);
  18515. __decorate([
  18516. BABYLON.serialize()
  18517. ], Camera.prototype, "interaxialDistance", void 0);
  18518. __decorate([
  18519. BABYLON.serialize()
  18520. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  18521. return Camera;
  18522. }(BABYLON.Node));
  18523. BABYLON.Camera = Camera;
  18524. })(BABYLON || (BABYLON = {}));
  18525. //# sourceMappingURL=babylon.camera.js.map
  18526. var BABYLON;
  18527. (function (BABYLON) {
  18528. var RenderingManager = /** @class */ (function () {
  18529. function RenderingManager(scene) {
  18530. this._renderingGroups = new Array();
  18531. this._autoClearDepthStencil = {};
  18532. this._customOpaqueSortCompareFn = {};
  18533. this._customAlphaTestSortCompareFn = {};
  18534. this._customTransparentSortCompareFn = {};
  18535. this._renderinGroupInfo = null;
  18536. this._scene = scene;
  18537. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18538. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18539. }
  18540. }
  18541. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18542. if (depth === void 0) { depth = true; }
  18543. if (stencil === void 0) { stencil = true; }
  18544. if (this._depthStencilBufferAlreadyCleaned) {
  18545. return;
  18546. }
  18547. this._scene.getEngine().clear(null, false, depth, stencil);
  18548. this._depthStencilBufferAlreadyCleaned = true;
  18549. };
  18550. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18551. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18552. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18553. var info = null;
  18554. if (observable) {
  18555. if (!this._renderinGroupInfo) {
  18556. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18557. }
  18558. info = this._renderinGroupInfo;
  18559. info.scene = this._scene;
  18560. info.camera = this._scene.activeCamera;
  18561. }
  18562. // Dispatch sprites
  18563. if (renderSprites) {
  18564. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18565. var manager = this._scene.spriteManagers[index];
  18566. this.dispatchSprites(manager);
  18567. }
  18568. }
  18569. // Render
  18570. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18571. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18572. var renderingGroup = this._renderingGroups[index];
  18573. if (!renderingGroup && !observable)
  18574. continue;
  18575. var renderingGroupMask = 0;
  18576. // Fire PRECLEAR stage
  18577. if (observable && info) {
  18578. renderingGroupMask = Math.pow(2, index);
  18579. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18580. info.renderingGroupId = index;
  18581. observable.notifyObservers(info, renderingGroupMask);
  18582. }
  18583. // Clear depth/stencil if needed
  18584. if (RenderingManager.AUTOCLEAR) {
  18585. var autoClear = this._autoClearDepthStencil[index];
  18586. if (autoClear && autoClear.autoClear) {
  18587. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18588. }
  18589. }
  18590. if (observable && info) {
  18591. // Fire PREOPAQUE stage
  18592. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18593. observable.notifyObservers(info, renderingGroupMask);
  18594. // Fire PRETRANSPARENT stage
  18595. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18596. observable.notifyObservers(info, renderingGroupMask);
  18597. }
  18598. if (renderingGroup)
  18599. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18600. // Fire POSTTRANSPARENT stage
  18601. if (observable && info) {
  18602. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18603. observable.notifyObservers(info, renderingGroupMask);
  18604. }
  18605. }
  18606. };
  18607. RenderingManager.prototype.reset = function () {
  18608. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18609. var renderingGroup = this._renderingGroups[index];
  18610. if (renderingGroup) {
  18611. renderingGroup.prepare();
  18612. }
  18613. }
  18614. };
  18615. RenderingManager.prototype.dispose = function () {
  18616. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18617. var renderingGroup = this._renderingGroups[index];
  18618. if (renderingGroup) {
  18619. renderingGroup.dispose();
  18620. }
  18621. }
  18622. this._renderingGroups.length = 0;
  18623. };
  18624. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18625. if (this._renderingGroups[renderingGroupId] === undefined) {
  18626. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18627. }
  18628. };
  18629. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18630. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18631. this._prepareRenderingGroup(renderingGroupId);
  18632. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18633. };
  18634. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18635. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18636. this._prepareRenderingGroup(renderingGroupId);
  18637. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18638. };
  18639. /**
  18640. * @param subMesh The submesh to dispatch
  18641. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18642. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18643. */
  18644. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  18645. if (mesh === undefined) {
  18646. mesh = subMesh.getMesh();
  18647. }
  18648. var renderingGroupId = mesh.renderingGroupId || 0;
  18649. this._prepareRenderingGroup(renderingGroupId);
  18650. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  18651. };
  18652. /**
  18653. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18654. * This allowed control for front to back rendering or reversly depending of the special needs.
  18655. *
  18656. * @param renderingGroupId The rendering group id corresponding to its index
  18657. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18658. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18659. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18660. */
  18661. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18662. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18663. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18664. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18665. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18666. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18667. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18668. if (this._renderingGroups[renderingGroupId]) {
  18669. var group = this._renderingGroups[renderingGroupId];
  18670. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18671. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18672. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18673. }
  18674. };
  18675. /**
  18676. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18677. *
  18678. * @param renderingGroupId The rendering group id corresponding to its index
  18679. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18680. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18681. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18682. */
  18683. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18684. if (depth === void 0) { depth = true; }
  18685. if (stencil === void 0) { stencil = true; }
  18686. this._autoClearDepthStencil[renderingGroupId] = {
  18687. autoClear: autoClearDepthStencil,
  18688. depth: depth,
  18689. stencil: stencil
  18690. };
  18691. };
  18692. /**
  18693. * The max id used for rendering groups (not included)
  18694. */
  18695. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18696. /**
  18697. * The min id used for rendering groups (included)
  18698. */
  18699. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18700. /**
  18701. * Used to globally prevent autoclearing scenes.
  18702. */
  18703. RenderingManager.AUTOCLEAR = true;
  18704. return RenderingManager;
  18705. }());
  18706. BABYLON.RenderingManager = RenderingManager;
  18707. })(BABYLON || (BABYLON = {}));
  18708. //# sourceMappingURL=babylon.renderingManager.js.map
  18709. var BABYLON;
  18710. (function (BABYLON) {
  18711. var RenderingGroup = /** @class */ (function () {
  18712. /**
  18713. * Creates a new rendering group.
  18714. * @param index The rendering group index
  18715. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18716. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18717. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18718. */
  18719. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18720. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18721. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18722. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18723. this.index = index;
  18724. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18725. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18726. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18727. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  18728. this._particleSystems = new BABYLON.SmartArray(256);
  18729. this._spriteManagers = new BABYLON.SmartArray(256);
  18730. this._edgesRenderers = new BABYLON.SmartArray(16);
  18731. this._scene = scene;
  18732. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18733. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18734. this.transparentSortCompareFn = transparentSortCompareFn;
  18735. }
  18736. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18737. /**
  18738. * Set the opaque sort comparison function.
  18739. * If null the sub meshes will be render in the order they were created
  18740. */
  18741. set: function (value) {
  18742. this._opaqueSortCompareFn = value;
  18743. if (value) {
  18744. this._renderOpaque = this.renderOpaqueSorted;
  18745. }
  18746. else {
  18747. this._renderOpaque = RenderingGroup.renderUnsorted;
  18748. }
  18749. },
  18750. enumerable: true,
  18751. configurable: true
  18752. });
  18753. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18754. /**
  18755. * Set the alpha test sort comparison function.
  18756. * If null the sub meshes will be render in the order they were created
  18757. */
  18758. set: function (value) {
  18759. this._alphaTestSortCompareFn = value;
  18760. if (value) {
  18761. this._renderAlphaTest = this.renderAlphaTestSorted;
  18762. }
  18763. else {
  18764. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  18765. }
  18766. },
  18767. enumerable: true,
  18768. configurable: true
  18769. });
  18770. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  18771. /**
  18772. * Set the transparent sort comparison function.
  18773. * If null the sub meshes will be render in the order they were created
  18774. */
  18775. set: function (value) {
  18776. if (value) {
  18777. this._transparentSortCompareFn = value;
  18778. }
  18779. else {
  18780. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  18781. }
  18782. this._renderTransparent = this.renderTransparentSorted;
  18783. },
  18784. enumerable: true,
  18785. configurable: true
  18786. });
  18787. /**
  18788. * Render all the sub meshes contained in the group.
  18789. * @param customRenderFunction Used to override the default render behaviour of the group.
  18790. * @returns true if rendered some submeshes.
  18791. */
  18792. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  18793. if (customRenderFunction) {
  18794. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  18795. return;
  18796. }
  18797. var engine = this._scene.getEngine();
  18798. // Depth only
  18799. if (this._depthOnlySubMeshes.length !== 0) {
  18800. engine.setAlphaTesting(true);
  18801. engine.setColorWrite(false);
  18802. this._renderAlphaTest(this._depthOnlySubMeshes);
  18803. engine.setAlphaTesting(false);
  18804. engine.setColorWrite(true);
  18805. }
  18806. // Opaque
  18807. if (this._opaqueSubMeshes.length !== 0) {
  18808. this._renderOpaque(this._opaqueSubMeshes);
  18809. }
  18810. // Alpha test
  18811. if (this._alphaTestSubMeshes.length !== 0) {
  18812. engine.setAlphaTesting(true);
  18813. this._renderAlphaTest(this._alphaTestSubMeshes);
  18814. engine.setAlphaTesting(false);
  18815. }
  18816. var stencilState = engine.getStencilBuffer();
  18817. engine.setStencilBuffer(false);
  18818. // Sprites
  18819. if (renderSprites) {
  18820. this._renderSprites();
  18821. }
  18822. // Particles
  18823. if (renderParticles) {
  18824. this._renderParticles(activeMeshes);
  18825. }
  18826. if (this.onBeforeTransparentRendering) {
  18827. this.onBeforeTransparentRendering();
  18828. }
  18829. // Transparent
  18830. if (this._transparentSubMeshes.length !== 0) {
  18831. this._renderTransparent(this._transparentSubMeshes);
  18832. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18833. }
  18834. // Set back stencil to false in case it changes before the edge renderer.
  18835. engine.setStencilBuffer(false);
  18836. // Edges
  18837. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18838. this._edgesRenderers.data[edgesRendererIndex].render();
  18839. }
  18840. // Restore Stencil state.
  18841. engine.setStencilBuffer(stencilState);
  18842. };
  18843. /**
  18844. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  18845. * @param subMeshes The submeshes to render
  18846. */
  18847. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  18848. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  18849. };
  18850. /**
  18851. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  18852. * @param subMeshes The submeshes to render
  18853. */
  18854. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  18855. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  18856. };
  18857. /**
  18858. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  18859. * @param subMeshes The submeshes to render
  18860. */
  18861. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18862. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  18863. };
  18864. /**
  18865. * Renders the submeshes in a specified order.
  18866. * @param subMeshes The submeshes to sort before render
  18867. * @param sortCompareFn The comparison function use to sort
  18868. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18869. * @param transparent Specifies to activate blending if true
  18870. */
  18871. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  18872. var subIndex = 0;
  18873. var subMesh;
  18874. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  18875. for (; subIndex < subMeshes.length; subIndex++) {
  18876. subMesh = subMeshes.data[subIndex];
  18877. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18878. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18879. }
  18880. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18881. if (sortCompareFn) {
  18882. sortedArray.sort(sortCompareFn);
  18883. }
  18884. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18885. subMesh = sortedArray[subIndex];
  18886. if (transparent) {
  18887. var material = subMesh.getMaterial();
  18888. if (material && material.needDepthPrePass) {
  18889. var engine = material.getScene().getEngine();
  18890. engine.setColorWrite(false);
  18891. engine.setAlphaTesting(true);
  18892. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18893. subMesh.render(false);
  18894. engine.setAlphaTesting(false);
  18895. engine.setColorWrite(true);
  18896. }
  18897. }
  18898. subMesh.render(transparent);
  18899. }
  18900. };
  18901. /**
  18902. * Renders the submeshes in the order they were dispatched (no sort applied).
  18903. * @param subMeshes The submeshes to render
  18904. */
  18905. RenderingGroup.renderUnsorted = function (subMeshes) {
  18906. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18907. var submesh = subMeshes.data[subIndex];
  18908. submesh.render(false);
  18909. }
  18910. };
  18911. /**
  18912. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18913. * are rendered back to front if in the same alpha index.
  18914. *
  18915. * @param a The first submesh
  18916. * @param b The second submesh
  18917. * @returns The result of the comparison
  18918. */
  18919. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  18920. // Alpha index first
  18921. if (a._alphaIndex > b._alphaIndex) {
  18922. return 1;
  18923. }
  18924. if (a._alphaIndex < b._alphaIndex) {
  18925. return -1;
  18926. }
  18927. // Then distance to camera
  18928. return RenderingGroup.backToFrontSortCompare(a, b);
  18929. };
  18930. /**
  18931. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18932. * are rendered back to front.
  18933. *
  18934. * @param a The first submesh
  18935. * @param b The second submesh
  18936. * @returns The result of the comparison
  18937. */
  18938. RenderingGroup.backToFrontSortCompare = function (a, b) {
  18939. // Then distance to camera
  18940. if (a._distanceToCamera < b._distanceToCamera) {
  18941. return 1;
  18942. }
  18943. if (a._distanceToCamera > b._distanceToCamera) {
  18944. return -1;
  18945. }
  18946. return 0;
  18947. };
  18948. /**
  18949. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18950. * are rendered front to back (prevent overdraw).
  18951. *
  18952. * @param a The first submesh
  18953. * @param b The second submesh
  18954. * @returns The result of the comparison
  18955. */
  18956. RenderingGroup.frontToBackSortCompare = function (a, b) {
  18957. // Then distance to camera
  18958. if (a._distanceToCamera < b._distanceToCamera) {
  18959. return -1;
  18960. }
  18961. if (a._distanceToCamera > b._distanceToCamera) {
  18962. return 1;
  18963. }
  18964. return 0;
  18965. };
  18966. /**
  18967. * Resets the different lists of submeshes to prepare a new frame.
  18968. */
  18969. RenderingGroup.prototype.prepare = function () {
  18970. this._opaqueSubMeshes.reset();
  18971. this._transparentSubMeshes.reset();
  18972. this._alphaTestSubMeshes.reset();
  18973. this._depthOnlySubMeshes.reset();
  18974. this._particleSystems.reset();
  18975. this._spriteManagers.reset();
  18976. this._edgesRenderers.reset();
  18977. };
  18978. RenderingGroup.prototype.dispose = function () {
  18979. this._opaqueSubMeshes.dispose();
  18980. this._transparentSubMeshes.dispose();
  18981. this._alphaTestSubMeshes.dispose();
  18982. this._depthOnlySubMeshes.dispose();
  18983. this._particleSystems.dispose();
  18984. this._spriteManagers.dispose();
  18985. this._edgesRenderers.dispose();
  18986. };
  18987. /**
  18988. * Inserts the submesh in its correct queue depending on its material.
  18989. * @param subMesh The submesh to dispatch
  18990. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18991. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18992. */
  18993. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  18994. // Get mesh and materials if not provided
  18995. if (mesh === undefined) {
  18996. mesh = subMesh.getMesh();
  18997. }
  18998. if (material === undefined) {
  18999. material = subMesh.getMaterial();
  19000. }
  19001. if (material === null || material === undefined) {
  19002. return;
  19003. }
  19004. if (material.needAlphaBlendingForMesh(mesh)) {
  19005. this._transparentSubMeshes.push(subMesh);
  19006. }
  19007. else if (material.needAlphaTesting()) {
  19008. if (material.needDepthPrePass) {
  19009. this._depthOnlySubMeshes.push(subMesh);
  19010. }
  19011. this._alphaTestSubMeshes.push(subMesh);
  19012. }
  19013. else {
  19014. if (material.needDepthPrePass) {
  19015. this._depthOnlySubMeshes.push(subMesh);
  19016. }
  19017. this._opaqueSubMeshes.push(subMesh); // Opaque
  19018. }
  19019. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19020. this._edgesRenderers.push(mesh._edgesRenderer);
  19021. }
  19022. };
  19023. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19024. this._spriteManagers.push(spriteManager);
  19025. };
  19026. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19027. this._particleSystems.push(particleSystem);
  19028. };
  19029. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19030. if (this._particleSystems.length === 0) {
  19031. return;
  19032. }
  19033. // Particles
  19034. var activeCamera = this._scene.activeCamera;
  19035. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19036. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19037. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19038. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19039. continue;
  19040. }
  19041. var emitter = particleSystem.emitter;
  19042. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19043. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19044. }
  19045. }
  19046. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19047. };
  19048. RenderingGroup.prototype._renderSprites = function () {
  19049. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19050. return;
  19051. }
  19052. // Sprites
  19053. var activeCamera = this._scene.activeCamera;
  19054. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19055. for (var id = 0; id < this._spriteManagers.length; id++) {
  19056. var spriteManager = this._spriteManagers.data[id];
  19057. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19058. spriteManager.render();
  19059. }
  19060. }
  19061. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19062. };
  19063. return RenderingGroup;
  19064. }());
  19065. BABYLON.RenderingGroup = RenderingGroup;
  19066. })(BABYLON || (BABYLON = {}));
  19067. //# sourceMappingURL=babylon.renderingGroup.js.map
  19068. var BABYLON;
  19069. (function (BABYLON) {
  19070. var ClickInfo = /** @class */ (function () {
  19071. function ClickInfo() {
  19072. this._singleClick = false;
  19073. this._doubleClick = false;
  19074. this._hasSwiped = false;
  19075. this._ignore = false;
  19076. }
  19077. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19078. get: function () {
  19079. return this._singleClick;
  19080. },
  19081. set: function (b) {
  19082. this._singleClick = b;
  19083. },
  19084. enumerable: true,
  19085. configurable: true
  19086. });
  19087. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19088. get: function () {
  19089. return this._doubleClick;
  19090. },
  19091. set: function (b) {
  19092. this._doubleClick = b;
  19093. },
  19094. enumerable: true,
  19095. configurable: true
  19096. });
  19097. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19098. get: function () {
  19099. return this._hasSwiped;
  19100. },
  19101. set: function (b) {
  19102. this._hasSwiped = b;
  19103. },
  19104. enumerable: true,
  19105. configurable: true
  19106. });
  19107. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19108. get: function () {
  19109. return this._ignore;
  19110. },
  19111. set: function (b) {
  19112. this._ignore = b;
  19113. },
  19114. enumerable: true,
  19115. configurable: true
  19116. });
  19117. return ClickInfo;
  19118. }());
  19119. /**
  19120. * This class is used by the onRenderingGroupObservable
  19121. */
  19122. var RenderingGroupInfo = /** @class */ (function () {
  19123. function RenderingGroupInfo() {
  19124. }
  19125. /**
  19126. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19127. * This stage will be fired no matter what
  19128. */
  19129. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19130. /**
  19131. * Called before opaque object are rendered.
  19132. * This stage will be fired only if there's 3D Opaque content to render
  19133. */
  19134. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19135. /**
  19136. * Called after the opaque objects are rendered and before the transparent ones
  19137. * This stage will be fired only if there's 3D transparent content to render
  19138. */
  19139. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19140. /**
  19141. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19142. * This stage will be fired no matter what
  19143. */
  19144. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19145. return RenderingGroupInfo;
  19146. }());
  19147. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19148. /**
  19149. * Represents a scene to be rendered by the engine.
  19150. * @see http://doc.babylonjs.com/page.php?p=21911
  19151. */
  19152. var Scene = /** @class */ (function () {
  19153. /**
  19154. * @constructor
  19155. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19156. */
  19157. function Scene(engine) {
  19158. // Members
  19159. this.autoClear = true;
  19160. this.autoClearDepthAndStencil = true;
  19161. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19162. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19163. this.forceWireframe = false;
  19164. this._forcePointsCloud = false;
  19165. this.forceShowBoundingBoxes = false;
  19166. this.animationsEnabled = true;
  19167. this.useConstantAnimationDeltaTime = false;
  19168. this.constantlyUpdateMeshUnderPointer = false;
  19169. this.hoverCursor = "pointer";
  19170. this.defaultCursor = "";
  19171. /**
  19172. * This is used to call preventDefault() on pointer down
  19173. * in order to block unwanted artifacts like system double clicks
  19174. */
  19175. this.preventDefaultOnPointerDown = true;
  19176. // Metadata
  19177. this.metadata = null;
  19178. /**
  19179. * An event triggered when the scene is disposed.
  19180. * @type {BABYLON.Observable}
  19181. */
  19182. this.onDisposeObservable = new BABYLON.Observable();
  19183. /**
  19184. * An event triggered before rendering the scene (right after animations and physics)
  19185. * @type {BABYLON.Observable}
  19186. */
  19187. this.onBeforeRenderObservable = new BABYLON.Observable();
  19188. /**
  19189. * An event triggered after rendering the scene
  19190. * @type {BABYLON.Observable}
  19191. */
  19192. this.onAfterRenderObservable = new BABYLON.Observable();
  19193. /**
  19194. * An event triggered before animating the scene
  19195. * @type {BABYLON.Observable}
  19196. */
  19197. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19198. /**
  19199. * An event triggered after animations processing
  19200. * @type {BABYLON.Observable}
  19201. */
  19202. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19203. /**
  19204. * An event triggered before draw calls are ready to be sent
  19205. * @type {BABYLON.Observable}
  19206. */
  19207. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19208. /**
  19209. * An event triggered after draw calls have been sent
  19210. * @type {BABYLON.Observable}
  19211. */
  19212. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19213. /**
  19214. * An event triggered when physic simulation is about to be run
  19215. * @type {BABYLON.Observable}
  19216. */
  19217. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19218. /**
  19219. * An event triggered when physic simulation has been done
  19220. * @type {BABYLON.Observable}
  19221. */
  19222. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19223. /**
  19224. * An event triggered when the scene is ready
  19225. * @type {BABYLON.Observable}
  19226. */
  19227. this.onReadyObservable = new BABYLON.Observable();
  19228. /**
  19229. * An event triggered before rendering a camera
  19230. * @type {BABYLON.Observable}
  19231. */
  19232. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19233. /**
  19234. * An event triggered after rendering a camera
  19235. * @type {BABYLON.Observable}
  19236. */
  19237. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19238. /**
  19239. * An event triggered when active meshes evaluation is about to start
  19240. * @type {BABYLON.Observable}
  19241. */
  19242. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19243. /**
  19244. * An event triggered when active meshes evaluation is done
  19245. * @type {BABYLON.Observable}
  19246. */
  19247. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19248. /**
  19249. * An event triggered when particles rendering is about to start
  19250. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19251. * @type {BABYLON.Observable}
  19252. */
  19253. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19254. /**
  19255. * An event triggered when particles rendering is done
  19256. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19257. * @type {BABYLON.Observable}
  19258. */
  19259. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19260. /**
  19261. * An event triggered when sprites rendering is about to start
  19262. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19263. * @type {BABYLON.Observable}
  19264. */
  19265. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19266. /**
  19267. * An event triggered when sprites rendering is done
  19268. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19269. * @type {BABYLON.Observable}
  19270. */
  19271. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19272. /**
  19273. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19274. * @type {BABYLON.Observable}
  19275. */
  19276. this.onDataLoadedObservable = new BABYLON.Observable();
  19277. /**
  19278. * An event triggered when a camera is created
  19279. * @type {BABYLON.Observable}
  19280. */
  19281. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19282. /**
  19283. * An event triggered when a camera is removed
  19284. * @type {BABYLON.Observable}
  19285. */
  19286. this.onCameraRemovedObservable = new BABYLON.Observable();
  19287. /**
  19288. * An event triggered when a light is created
  19289. * @type {BABYLON.Observable}
  19290. */
  19291. this.onNewLightAddedObservable = new BABYLON.Observable();
  19292. /**
  19293. * An event triggered when a light is removed
  19294. * @type {BABYLON.Observable}
  19295. */
  19296. this.onLightRemovedObservable = new BABYLON.Observable();
  19297. /**
  19298. * An event triggered when a geometry is created
  19299. * @type {BABYLON.Observable}
  19300. */
  19301. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19302. /**
  19303. * An event triggered when a geometry is removed
  19304. * @type {BABYLON.Observable}
  19305. */
  19306. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19307. /**
  19308. * An event triggered when a transform node is created
  19309. * @type {BABYLON.Observable}
  19310. */
  19311. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19312. /**
  19313. * An event triggered when a transform node is removed
  19314. * @type {BABYLON.Observable}
  19315. */
  19316. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19317. /**
  19318. * An event triggered when a mesh is created
  19319. * @type {BABYLON.Observable}
  19320. */
  19321. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19322. /**
  19323. * An event triggered when a mesh is removed
  19324. * @type {BABYLON.Observable}
  19325. */
  19326. this.onMeshRemovedObservable = new BABYLON.Observable();
  19327. /**
  19328. * An event triggered when render targets are about to be rendered
  19329. * Can happen multiple times per frame.
  19330. * @type {BABYLON.Observable}
  19331. */
  19332. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19333. /**
  19334. * An event triggered when render targets were rendered.
  19335. * Can happen multiple times per frame.
  19336. * @type {BABYLON.Observable}
  19337. */
  19338. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19339. /**
  19340. * An event triggered before calculating deterministic simulation step
  19341. * @type {BABYLON.Observable}
  19342. */
  19343. this.onBeforeStepObservable = new BABYLON.Observable();
  19344. /**
  19345. * An event triggered after calculating deterministic simulation step
  19346. * @type {BABYLON.Observable}
  19347. */
  19348. this.onAfterStepObservable = new BABYLON.Observable();
  19349. /**
  19350. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19351. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19352. * 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)
  19353. */
  19354. this.onRenderingGroupObservable = new BABYLON.Observable();
  19355. // Animations
  19356. this.animations = [];
  19357. /**
  19358. * 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).
  19359. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19360. */
  19361. this.onPrePointerObservable = new BABYLON.Observable();
  19362. /**
  19363. * Observable event triggered each time an input event is received from the rendering canvas
  19364. */
  19365. this.onPointerObservable = new BABYLON.Observable();
  19366. this._meshPickProceed = false;
  19367. this._currentPickResult = null;
  19368. this._previousPickResult = null;
  19369. this._totalPointersPressed = 0;
  19370. this._doubleClickOccured = false;
  19371. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19372. this.cameraToUseForPointers = null;
  19373. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19374. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19375. this._startingPointerTime = 0;
  19376. this._previousStartingPointerTime = 0;
  19377. // Deterministic lockstep
  19378. this._timeAccumulator = 0;
  19379. this._currentStepId = 0;
  19380. this._currentInternalStep = 0;
  19381. // Keyboard
  19382. /**
  19383. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19384. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19385. */
  19386. this.onPreKeyboardObservable = new BABYLON.Observable();
  19387. /**
  19388. * Observable event triggered each time an keyboard event is received from the hosting window
  19389. */
  19390. this.onKeyboardObservable = new BABYLON.Observable();
  19391. // Coordinate system
  19392. /**
  19393. * use right-handed coordinate system on this scene.
  19394. * @type {boolean}
  19395. */
  19396. this._useRightHandedSystem = false;
  19397. // Fog
  19398. this._fogEnabled = true;
  19399. this._fogMode = Scene.FOGMODE_NONE;
  19400. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19401. this.fogDensity = 0.1;
  19402. this.fogStart = 0;
  19403. this.fogEnd = 1000.0;
  19404. // Lights
  19405. /**
  19406. * is shadow enabled on this scene.
  19407. * @type {boolean}
  19408. */
  19409. this._shadowsEnabled = true;
  19410. /**
  19411. * is light enabled on this scene.
  19412. * @type {boolean}
  19413. */
  19414. this._lightsEnabled = true;
  19415. /**
  19416. * All of the lights added to this scene.
  19417. * @see BABYLON.Light
  19418. * @type {BABYLON.Light[]}
  19419. */
  19420. this.lights = new Array();
  19421. // Cameras
  19422. /** All of the cameras added to this scene. */
  19423. this.cameras = new Array();
  19424. /** All of the active cameras added to this scene. */
  19425. this.activeCameras = new Array();
  19426. // Meshes
  19427. /**
  19428. * All of the tranform nodes added to this scene.
  19429. * @see BABYLON.TransformNode
  19430. * @type {BABYLON.TransformNode[]}
  19431. */
  19432. this.transformNodes = new Array();
  19433. /**
  19434. * All of the (abstract) meshes added to this scene.
  19435. * @see BABYLON.AbstractMesh
  19436. * @type {BABYLON.AbstractMesh[]}
  19437. */
  19438. this.meshes = new Array();
  19439. /**
  19440. * All of the animation groups added to this scene.
  19441. * @see BABYLON.AnimationGroup
  19442. * @type {BABYLON.AnimationGroup[]}
  19443. */
  19444. this.animationGroups = new Array();
  19445. // Geometries
  19446. this._geometries = new Array();
  19447. this.materials = new Array();
  19448. this.multiMaterials = new Array();
  19449. // Textures
  19450. this._texturesEnabled = true;
  19451. this.textures = new Array();
  19452. // Particles
  19453. this.particlesEnabled = true;
  19454. this.particleSystems = new Array();
  19455. // Sprites
  19456. this.spritesEnabled = true;
  19457. this.spriteManagers = new Array();
  19458. // Layers
  19459. this.layers = new Array();
  19460. this.highlightLayers = new Array();
  19461. // Skeletons
  19462. this._skeletonsEnabled = true;
  19463. this.skeletons = new Array();
  19464. // Morph targets
  19465. this.morphTargetManagers = new Array();
  19466. // Lens flares
  19467. this.lensFlaresEnabled = true;
  19468. this.lensFlareSystems = new Array();
  19469. // Collisions
  19470. this.collisionsEnabled = true;
  19471. /** Defines the gravity applied to this scene */
  19472. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19473. // Postprocesses
  19474. this.postProcesses = new Array();
  19475. this.postProcessesEnabled = true;
  19476. // Customs render targets
  19477. this.renderTargetsEnabled = true;
  19478. this.dumpNextRenderTargets = false;
  19479. this.customRenderTargets = new Array();
  19480. // Imported meshes
  19481. this.importedMeshesFiles = new Array();
  19482. // Probes
  19483. this.probesEnabled = true;
  19484. this.reflectionProbes = new Array();
  19485. this._actionManagers = new Array();
  19486. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  19487. // Procedural textures
  19488. this.proceduralTexturesEnabled = true;
  19489. this._proceduralTextures = new Array();
  19490. this.soundTracks = new Array();
  19491. this._audioEnabled = true;
  19492. this._headphone = false;
  19493. // Performance counters
  19494. this._totalVertices = new BABYLON.PerfCounter();
  19495. this._activeIndices = new BABYLON.PerfCounter();
  19496. this._activeParticles = new BABYLON.PerfCounter();
  19497. this._activeBones = new BABYLON.PerfCounter();
  19498. this._animationTime = 0;
  19499. this.animationTimeScale = 1;
  19500. this._renderId = 0;
  19501. this._executeWhenReadyTimeoutId = -1;
  19502. this._intermediateRendering = false;
  19503. this._viewUpdateFlag = -1;
  19504. this._projectionUpdateFlag = -1;
  19505. this._alternateViewUpdateFlag = -1;
  19506. this._alternateProjectionUpdateFlag = -1;
  19507. this._toBeDisposed = new BABYLON.SmartArray(256);
  19508. this._activeRequests = new Array();
  19509. this._pendingData = new Array();
  19510. this._isDisposed = false;
  19511. this.dispatchAllSubMeshesOfActiveMeshes = false;
  19512. this._activeMeshes = new BABYLON.SmartArray(256);
  19513. this._processedMaterials = new BABYLON.SmartArray(256);
  19514. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  19515. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19516. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  19517. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  19518. this._activeAnimatables = new Array();
  19519. this._transformMatrix = BABYLON.Matrix.Zero();
  19520. this._useAlternateCameraConfiguration = false;
  19521. this._alternateRendering = false;
  19522. this.requireLightSorting = false;
  19523. this._activeMeshesFrozen = false;
  19524. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  19525. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19526. this._engine.scenes.push(this);
  19527. this._uid = null;
  19528. this._renderingManager = new BABYLON.RenderingManager(this);
  19529. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19530. if (BABYLON.OutlineRenderer) {
  19531. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19532. }
  19533. if (BABYLON.Tools.IsWindowObjectExist()) {
  19534. this.attachControl();
  19535. }
  19536. //simplification queue
  19537. if (BABYLON.SimplificationQueue) {
  19538. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19539. }
  19540. //collision coordinator initialization. For now legacy per default.
  19541. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19542. // Uniform Buffer
  19543. this._createUbo();
  19544. // Default Image processing definition.
  19545. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  19546. }
  19547. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19548. /** The fog is deactivated */
  19549. get: function () {
  19550. return Scene._FOGMODE_NONE;
  19551. },
  19552. enumerable: true,
  19553. configurable: true
  19554. });
  19555. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19556. /** The fog density is following an exponential function */
  19557. get: function () {
  19558. return Scene._FOGMODE_EXP;
  19559. },
  19560. enumerable: true,
  19561. configurable: true
  19562. });
  19563. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19564. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  19565. get: function () {
  19566. return Scene._FOGMODE_EXP2;
  19567. },
  19568. enumerable: true,
  19569. configurable: true
  19570. });
  19571. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19572. /** The fog density is following a linear function. */
  19573. get: function () {
  19574. return Scene._FOGMODE_LINEAR;
  19575. },
  19576. enumerable: true,
  19577. configurable: true
  19578. });
  19579. Object.defineProperty(Scene.prototype, "environmentTexture", {
  19580. /**
  19581. * Texture used in all pbr material as the reflection texture.
  19582. * As in the majority of the scene they are the same (exception for multi room and so on),
  19583. * this is easier to reference from here than from all the materials.
  19584. */
  19585. get: function () {
  19586. return this._environmentTexture;
  19587. },
  19588. /**
  19589. * Texture used in all pbr material as the reflection texture.
  19590. * As in the majority of the scene they are the same (exception for multi room and so on),
  19591. * this is easier to set here than in all the materials.
  19592. */
  19593. set: function (value) {
  19594. if (this._environmentTexture === value) {
  19595. return;
  19596. }
  19597. this._environmentTexture = value;
  19598. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19599. },
  19600. enumerable: true,
  19601. configurable: true
  19602. });
  19603. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  19604. /**
  19605. * Default image processing configuration used either in the rendering
  19606. * Forward main pass or through the imageProcessingPostProcess if present.
  19607. * As in the majority of the scene they are the same (exception for multi camera),
  19608. * this is easier to reference from here than from all the materials and post process.
  19609. *
  19610. * No setter as we it is a shared configuration, you can set the values instead.
  19611. */
  19612. get: function () {
  19613. return this._imageProcessingConfiguration;
  19614. },
  19615. enumerable: true,
  19616. configurable: true
  19617. });
  19618. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  19619. get: function () {
  19620. return this._forcePointsCloud;
  19621. },
  19622. set: function (value) {
  19623. if (this._forcePointsCloud === value) {
  19624. return;
  19625. }
  19626. this._forcePointsCloud = value;
  19627. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19628. },
  19629. enumerable: true,
  19630. configurable: true
  19631. });
  19632. Object.defineProperty(Scene.prototype, "onDispose", {
  19633. /** A function to be executed when this scene is disposed. */
  19634. set: function (callback) {
  19635. if (this._onDisposeObserver) {
  19636. this.onDisposeObservable.remove(this._onDisposeObserver);
  19637. }
  19638. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19639. },
  19640. enumerable: true,
  19641. configurable: true
  19642. });
  19643. Object.defineProperty(Scene.prototype, "beforeRender", {
  19644. /** A function to be executed before rendering this scene */
  19645. set: function (callback) {
  19646. if (this._onBeforeRenderObserver) {
  19647. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19648. }
  19649. if (callback) {
  19650. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19651. }
  19652. },
  19653. enumerable: true,
  19654. configurable: true
  19655. });
  19656. Object.defineProperty(Scene.prototype, "afterRender", {
  19657. /** A function to be executed after rendering this scene */
  19658. set: function (callback) {
  19659. if (this._onAfterRenderObserver) {
  19660. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19661. }
  19662. if (callback) {
  19663. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19664. }
  19665. },
  19666. enumerable: true,
  19667. configurable: true
  19668. });
  19669. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19670. set: function (callback) {
  19671. if (this._onBeforeCameraRenderObserver) {
  19672. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19673. }
  19674. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19675. },
  19676. enumerable: true,
  19677. configurable: true
  19678. });
  19679. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19680. set: function (callback) {
  19681. if (this._onAfterCameraRenderObserver) {
  19682. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19683. }
  19684. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19685. },
  19686. enumerable: true,
  19687. configurable: true
  19688. });
  19689. Object.defineProperty(Scene.prototype, "gamepadManager", {
  19690. get: function () {
  19691. if (!this._gamepadManager) {
  19692. this._gamepadManager = new BABYLON.GamepadManager(this);
  19693. }
  19694. return this._gamepadManager;
  19695. },
  19696. enumerable: true,
  19697. configurable: true
  19698. });
  19699. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19700. get: function () {
  19701. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19702. },
  19703. enumerable: true,
  19704. configurable: true
  19705. });
  19706. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  19707. get: function () {
  19708. return this._useRightHandedSystem;
  19709. },
  19710. set: function (value) {
  19711. if (this._useRightHandedSystem === value) {
  19712. return;
  19713. }
  19714. this._useRightHandedSystem = value;
  19715. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19716. },
  19717. enumerable: true,
  19718. configurable: true
  19719. });
  19720. Scene.prototype.setStepId = function (newStepId) {
  19721. this._currentStepId = newStepId;
  19722. };
  19723. ;
  19724. Scene.prototype.getStepId = function () {
  19725. return this._currentStepId;
  19726. };
  19727. ;
  19728. Scene.prototype.getInternalStep = function () {
  19729. return this._currentInternalStep;
  19730. };
  19731. ;
  19732. Object.defineProperty(Scene.prototype, "fogEnabled", {
  19733. get: function () {
  19734. return this._fogEnabled;
  19735. },
  19736. /**
  19737. * is fog enabled on this scene.
  19738. */
  19739. set: function (value) {
  19740. if (this._fogEnabled === value) {
  19741. return;
  19742. }
  19743. this._fogEnabled = value;
  19744. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19745. },
  19746. enumerable: true,
  19747. configurable: true
  19748. });
  19749. Object.defineProperty(Scene.prototype, "fogMode", {
  19750. get: function () {
  19751. return this._fogMode;
  19752. },
  19753. set: function (value) {
  19754. if (this._fogMode === value) {
  19755. return;
  19756. }
  19757. this._fogMode = value;
  19758. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19759. },
  19760. enumerable: true,
  19761. configurable: true
  19762. });
  19763. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  19764. get: function () {
  19765. return this._shadowsEnabled;
  19766. },
  19767. set: function (value) {
  19768. if (this._shadowsEnabled === value) {
  19769. return;
  19770. }
  19771. this._shadowsEnabled = value;
  19772. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19773. },
  19774. enumerable: true,
  19775. configurable: true
  19776. });
  19777. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  19778. get: function () {
  19779. return this._lightsEnabled;
  19780. },
  19781. set: function (value) {
  19782. if (this._lightsEnabled === value) {
  19783. return;
  19784. }
  19785. this._lightsEnabled = value;
  19786. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19787. },
  19788. enumerable: true,
  19789. configurable: true
  19790. });
  19791. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19792. /** The default material used on meshes when no material is affected */
  19793. get: function () {
  19794. if (!this._defaultMaterial) {
  19795. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19796. }
  19797. return this._defaultMaterial;
  19798. },
  19799. /** The default material used on meshes when no material is affected */
  19800. set: function (value) {
  19801. this._defaultMaterial = value;
  19802. },
  19803. enumerable: true,
  19804. configurable: true
  19805. });
  19806. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  19807. get: function () {
  19808. return this._texturesEnabled;
  19809. },
  19810. set: function (value) {
  19811. if (this._texturesEnabled === value) {
  19812. return;
  19813. }
  19814. this._texturesEnabled = value;
  19815. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19816. },
  19817. enumerable: true,
  19818. configurable: true
  19819. });
  19820. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  19821. get: function () {
  19822. return this._skeletonsEnabled;
  19823. },
  19824. set: function (value) {
  19825. if (this._skeletonsEnabled === value) {
  19826. return;
  19827. }
  19828. this._skeletonsEnabled = value;
  19829. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  19830. },
  19831. enumerable: true,
  19832. configurable: true
  19833. });
  19834. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  19835. get: function () {
  19836. if (!this._postProcessRenderPipelineManager) {
  19837. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19838. }
  19839. return this._postProcessRenderPipelineManager;
  19840. },
  19841. enumerable: true,
  19842. configurable: true
  19843. });
  19844. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  19845. get: function () {
  19846. if (!this._mainSoundTrack) {
  19847. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19848. }
  19849. return this._mainSoundTrack;
  19850. },
  19851. enumerable: true,
  19852. configurable: true
  19853. });
  19854. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  19855. get: function () {
  19856. return this._alternateRendering;
  19857. },
  19858. enumerable: true,
  19859. configurable: true
  19860. });
  19861. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19862. get: function () {
  19863. return this._frustumPlanes;
  19864. },
  19865. enumerable: true,
  19866. configurable: true
  19867. });
  19868. Object.defineProperty(Scene.prototype, "debugLayer", {
  19869. // Properties
  19870. get: function () {
  19871. if (!this._debugLayer) {
  19872. this._debugLayer = new BABYLON.DebugLayer(this);
  19873. }
  19874. return this._debugLayer;
  19875. },
  19876. enumerable: true,
  19877. configurable: true
  19878. });
  19879. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19880. get: function () {
  19881. return this._workerCollisions;
  19882. },
  19883. set: function (enabled) {
  19884. if (!BABYLON.CollisionCoordinatorLegacy) {
  19885. return;
  19886. }
  19887. enabled = (enabled && !!Worker);
  19888. this._workerCollisions = enabled;
  19889. if (this.collisionCoordinator) {
  19890. this.collisionCoordinator.destroy();
  19891. }
  19892. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19893. this.collisionCoordinator.init(this);
  19894. },
  19895. enumerable: true,
  19896. configurable: true
  19897. });
  19898. Object.defineProperty(Scene.prototype, "selectionOctree", {
  19899. get: function () {
  19900. return this._selectionOctree;
  19901. },
  19902. enumerable: true,
  19903. configurable: true
  19904. });
  19905. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19906. /**
  19907. * The mesh that is currently under the pointer.
  19908. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19909. */
  19910. get: function () {
  19911. return this._pointerOverMesh;
  19912. },
  19913. enumerable: true,
  19914. configurable: true
  19915. });
  19916. Object.defineProperty(Scene.prototype, "pointerX", {
  19917. /**
  19918. * Current on-screen X position of the pointer
  19919. * @return {number} X position of the pointer
  19920. */
  19921. get: function () {
  19922. return this._pointerX;
  19923. },
  19924. enumerable: true,
  19925. configurable: true
  19926. });
  19927. Object.defineProperty(Scene.prototype, "pointerY", {
  19928. /**
  19929. * Current on-screen Y position of the pointer
  19930. * @return {number} Y position of the pointer
  19931. */
  19932. get: function () {
  19933. return this._pointerY;
  19934. },
  19935. enumerable: true,
  19936. configurable: true
  19937. });
  19938. Scene.prototype.getCachedMaterial = function () {
  19939. return this._cachedMaterial;
  19940. };
  19941. Scene.prototype.getCachedEffect = function () {
  19942. return this._cachedEffect;
  19943. };
  19944. Scene.prototype.getCachedVisibility = function () {
  19945. return this._cachedVisibility;
  19946. };
  19947. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  19948. if (visibility === void 0) { visibility = 1; }
  19949. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  19950. };
  19951. Scene.prototype.getBoundingBoxRenderer = function () {
  19952. if (!this._boundingBoxRenderer) {
  19953. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19954. }
  19955. return this._boundingBoxRenderer;
  19956. };
  19957. Scene.prototype.getOutlineRenderer = function () {
  19958. return this._outlineRenderer;
  19959. };
  19960. Scene.prototype.getEngine = function () {
  19961. return this._engine;
  19962. };
  19963. Scene.prototype.getTotalVertices = function () {
  19964. return this._totalVertices.current;
  19965. };
  19966. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19967. get: function () {
  19968. return this._totalVertices;
  19969. },
  19970. enumerable: true,
  19971. configurable: true
  19972. });
  19973. Scene.prototype.getActiveIndices = function () {
  19974. return this._activeIndices.current;
  19975. };
  19976. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19977. get: function () {
  19978. return this._activeIndices;
  19979. },
  19980. enumerable: true,
  19981. configurable: true
  19982. });
  19983. Scene.prototype.getActiveParticles = function () {
  19984. return this._activeParticles.current;
  19985. };
  19986. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  19987. get: function () {
  19988. return this._activeParticles;
  19989. },
  19990. enumerable: true,
  19991. configurable: true
  19992. });
  19993. Scene.prototype.getActiveBones = function () {
  19994. return this._activeBones.current;
  19995. };
  19996. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  19997. get: function () {
  19998. return this._activeBones;
  19999. },
  20000. enumerable: true,
  20001. configurable: true
  20002. });
  20003. // Stats
  20004. Scene.prototype.getInterFramePerfCounter = function () {
  20005. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20006. return 0;
  20007. };
  20008. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20009. get: function () {
  20010. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20011. return null;
  20012. },
  20013. enumerable: true,
  20014. configurable: true
  20015. });
  20016. Scene.prototype.getLastFrameDuration = function () {
  20017. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20018. return 0;
  20019. };
  20020. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20021. get: function () {
  20022. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20023. return null;
  20024. },
  20025. enumerable: true,
  20026. configurable: true
  20027. });
  20028. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20029. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20030. return 0;
  20031. };
  20032. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20033. get: function () {
  20034. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20035. return null;
  20036. },
  20037. enumerable: true,
  20038. configurable: true
  20039. });
  20040. Scene.prototype.getActiveMeshes = function () {
  20041. return this._activeMeshes;
  20042. };
  20043. Scene.prototype.getRenderTargetsDuration = function () {
  20044. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20045. return 0;
  20046. };
  20047. Scene.prototype.getRenderDuration = function () {
  20048. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20049. return 0;
  20050. };
  20051. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20052. get: function () {
  20053. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20054. return null;
  20055. },
  20056. enumerable: true,
  20057. configurable: true
  20058. });
  20059. Scene.prototype.getParticlesDuration = function () {
  20060. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20061. return 0;
  20062. };
  20063. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20064. get: function () {
  20065. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20066. return null;
  20067. },
  20068. enumerable: true,
  20069. configurable: true
  20070. });
  20071. Scene.prototype.getSpritesDuration = function () {
  20072. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20073. return 0;
  20074. };
  20075. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20076. get: function () {
  20077. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20078. return null;
  20079. },
  20080. enumerable: true,
  20081. configurable: true
  20082. });
  20083. Scene.prototype.getAnimationRatio = function () {
  20084. return this._animationRatio;
  20085. };
  20086. Scene.prototype.getRenderId = function () {
  20087. return this._renderId;
  20088. };
  20089. Scene.prototype.incrementRenderId = function () {
  20090. this._renderId++;
  20091. };
  20092. Scene.prototype._updatePointerPosition = function (evt) {
  20093. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20094. if (!canvasRect) {
  20095. return;
  20096. }
  20097. this._pointerX = evt.clientX - canvasRect.left;
  20098. this._pointerY = evt.clientY - canvasRect.top;
  20099. this._unTranslatedPointerX = this._pointerX;
  20100. this._unTranslatedPointerY = this._pointerY;
  20101. };
  20102. Scene.prototype._createUbo = function () {
  20103. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20104. this._sceneUbo.addUniform("viewProjection", 16);
  20105. this._sceneUbo.addUniform("view", 16);
  20106. };
  20107. Scene.prototype._createAlternateUbo = function () {
  20108. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20109. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20110. this._alternateSceneUbo.addUniform("view", 16);
  20111. };
  20112. // Pointers handling
  20113. /**
  20114. * Use this method to simulate a pointer move on a mesh
  20115. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20116. */
  20117. Scene.prototype.simulatePointerMove = function (pickResult) {
  20118. var evt = new PointerEvent("pointermove");
  20119. return this._processPointerMove(pickResult, evt);
  20120. };
  20121. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20122. var canvas = this._engine.getRenderingCanvas();
  20123. if (!canvas) {
  20124. return this;
  20125. }
  20126. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20127. this.setPointerOverSprite(null);
  20128. this.setPointerOverMesh(pickResult.pickedMesh);
  20129. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20130. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20131. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20132. }
  20133. else {
  20134. canvas.style.cursor = this.hoverCursor;
  20135. }
  20136. }
  20137. else {
  20138. canvas.style.cursor = this.defaultCursor;
  20139. }
  20140. }
  20141. else {
  20142. this.setPointerOverMesh(null);
  20143. // Sprites
  20144. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20145. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20146. this.setPointerOverSprite(pickResult.pickedSprite);
  20147. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20148. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20149. }
  20150. else {
  20151. canvas.style.cursor = this.hoverCursor;
  20152. }
  20153. }
  20154. else {
  20155. this.setPointerOverSprite(null);
  20156. // Restore pointer
  20157. canvas.style.cursor = this.defaultCursor;
  20158. }
  20159. }
  20160. if (pickResult) {
  20161. if (this.onPointerMove) {
  20162. this.onPointerMove(evt, pickResult);
  20163. }
  20164. if (this.onPointerObservable.hasObservers()) {
  20165. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20166. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20167. this.onPointerObservable.notifyObservers(pi, type);
  20168. }
  20169. }
  20170. return this;
  20171. };
  20172. /**
  20173. * Use this method to simulate a pointer down on a mesh
  20174. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20175. */
  20176. Scene.prototype.simulatePointerDown = function (pickResult) {
  20177. var evt = new PointerEvent("pointerdown");
  20178. return this._processPointerDown(pickResult, evt);
  20179. };
  20180. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20181. var _this = this;
  20182. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20183. this._pickedDownMesh = pickResult.pickedMesh;
  20184. var actionManager = pickResult.pickedMesh.actionManager;
  20185. if (actionManager) {
  20186. if (actionManager.hasPickTriggers) {
  20187. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20188. switch (evt.button) {
  20189. case 0:
  20190. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20191. break;
  20192. case 1:
  20193. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20194. break;
  20195. case 2:
  20196. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20197. break;
  20198. }
  20199. }
  20200. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20201. window.setTimeout(function () {
  20202. 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);
  20203. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20204. if (_this._totalPointersPressed !== 0 &&
  20205. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20206. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20207. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20208. _this._startingPointerTime = 0;
  20209. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20210. }
  20211. }
  20212. }, Scene.LongPressDelay);
  20213. }
  20214. }
  20215. }
  20216. if (pickResult) {
  20217. if (this.onPointerDown) {
  20218. this.onPointerDown(evt, pickResult);
  20219. }
  20220. if (this.onPointerObservable.hasObservers()) {
  20221. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20222. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20223. this.onPointerObservable.notifyObservers(pi, type);
  20224. }
  20225. }
  20226. return this;
  20227. };
  20228. /**
  20229. * Use this method to simulate a pointer up on a mesh
  20230. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20231. */
  20232. Scene.prototype.simulatePointerUp = function (pickResult) {
  20233. var evt = new PointerEvent("pointerup");
  20234. var clickInfo = new ClickInfo();
  20235. clickInfo.singleClick = true;
  20236. clickInfo.ignore = true;
  20237. return this._processPointerUp(pickResult, evt, clickInfo);
  20238. };
  20239. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20240. if (pickResult && pickResult && pickResult.pickedMesh) {
  20241. this._pickedUpMesh = pickResult.pickedMesh;
  20242. if (this._pickedDownMesh === this._pickedUpMesh) {
  20243. if (this.onPointerPick) {
  20244. this.onPointerPick(evt, pickResult);
  20245. }
  20246. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20247. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20248. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20249. this.onPointerObservable.notifyObservers(pi, type);
  20250. }
  20251. }
  20252. if (pickResult.pickedMesh.actionManager) {
  20253. if (clickInfo.ignore) {
  20254. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20255. }
  20256. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20257. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20258. }
  20259. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20260. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20261. }
  20262. }
  20263. }
  20264. if (this._pickedDownMesh &&
  20265. this._pickedDownMesh.actionManager &&
  20266. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20267. this._pickedDownMesh !== this._pickedUpMesh) {
  20268. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20269. }
  20270. if (this.onPointerUp) {
  20271. this.onPointerUp(evt, pickResult);
  20272. }
  20273. if (this.onPointerObservable.hasObservers()) {
  20274. if (!clickInfo.ignore) {
  20275. if (!clickInfo.hasSwiped) {
  20276. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20277. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20278. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20279. this.onPointerObservable.notifyObservers(pi, type);
  20280. }
  20281. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20282. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20283. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20284. this.onPointerObservable.notifyObservers(pi, type);
  20285. }
  20286. }
  20287. }
  20288. else {
  20289. var type = BABYLON.PointerEventTypes.POINTERUP;
  20290. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20291. this.onPointerObservable.notifyObservers(pi, type);
  20292. }
  20293. }
  20294. return this;
  20295. };
  20296. /**
  20297. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20298. * @param attachUp defines if you want to attach events to pointerup
  20299. * @param attachDown defines if you want to attach events to pointerdown
  20300. * @param attachMove defines if you want to attach events to pointermove
  20301. */
  20302. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20303. var _this = this;
  20304. if (attachUp === void 0) { attachUp = true; }
  20305. if (attachDown === void 0) { attachDown = true; }
  20306. if (attachMove === void 0) { attachMove = true; }
  20307. this._initActionManager = function (act, clickInfo) {
  20308. if (!_this._meshPickProceed) {
  20309. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20310. _this._currentPickResult = pickResult;
  20311. if (pickResult) {
  20312. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20313. }
  20314. _this._meshPickProceed = true;
  20315. }
  20316. return act;
  20317. };
  20318. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20319. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20320. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20321. btn !== _this._previousButtonPressed) {
  20322. _this._doubleClickOccured = false;
  20323. clickInfo.singleClick = true;
  20324. clickInfo.ignore = false;
  20325. cb(clickInfo, _this._currentPickResult);
  20326. }
  20327. };
  20328. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20329. var clickInfo = new ClickInfo();
  20330. _this._currentPickResult = null;
  20331. var act = null;
  20332. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20333. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20334. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20335. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20336. act = _this._initActionManager(act, clickInfo);
  20337. if (act)
  20338. checkPicking = act.hasPickTriggers;
  20339. }
  20340. if (checkPicking) {
  20341. var btn = evt.button;
  20342. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20343. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20344. if (!clickInfo.hasSwiped) {
  20345. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20346. if (!checkSingleClickImmediately) {
  20347. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20348. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20349. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20350. act = _this._initActionManager(act, clickInfo);
  20351. if (act)
  20352. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20353. }
  20354. }
  20355. if (checkSingleClickImmediately) {
  20356. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20357. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20358. btn !== _this._previousButtonPressed) {
  20359. clickInfo.singleClick = true;
  20360. cb(clickInfo, _this._currentPickResult);
  20361. }
  20362. }
  20363. else {
  20364. // wait that no double click has been raised during the double click delay
  20365. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20366. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20367. }
  20368. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20369. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20370. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20371. act = _this._initActionManager(act, clickInfo);
  20372. if (act)
  20373. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20374. }
  20375. if (checkDoubleClick) {
  20376. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20377. if (btn === _this._previousButtonPressed &&
  20378. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20379. !_this._doubleClickOccured) {
  20380. // pointer has not moved for 2 clicks, it's a double click
  20381. if (!clickInfo.hasSwiped &&
  20382. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20383. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20384. _this._previousStartingPointerTime = 0;
  20385. _this._doubleClickOccured = true;
  20386. clickInfo.doubleClick = true;
  20387. clickInfo.ignore = false;
  20388. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20389. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20390. }
  20391. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20392. cb(clickInfo, _this._currentPickResult);
  20393. }
  20394. else {
  20395. _this._doubleClickOccured = false;
  20396. _this._previousStartingPointerTime = _this._startingPointerTime;
  20397. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20398. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20399. _this._previousButtonPressed = btn;
  20400. if (Scene.ExclusiveDoubleClickMode) {
  20401. if (_this._previousDelayedSimpleClickTimeout) {
  20402. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20403. }
  20404. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20405. cb(clickInfo, _this._previousPickResult);
  20406. }
  20407. else {
  20408. cb(clickInfo, _this._currentPickResult);
  20409. }
  20410. }
  20411. }
  20412. else {
  20413. _this._doubleClickOccured = false;
  20414. _this._previousStartingPointerTime = _this._startingPointerTime;
  20415. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20416. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20417. _this._previousButtonPressed = btn;
  20418. }
  20419. }
  20420. }
  20421. }
  20422. clickInfo.ignore = true;
  20423. cb(clickInfo, _this._currentPickResult);
  20424. };
  20425. this._spritePredicate = function (sprite) {
  20426. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20427. };
  20428. this._onPointerMove = function (evt) {
  20429. _this._updatePointerPosition(evt);
  20430. // PreObservable support
  20431. if (_this.onPrePointerObservable.hasObservers()) {
  20432. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20433. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20434. _this.onPrePointerObservable.notifyObservers(pi, type);
  20435. if (pi.skipOnPointerObservable) {
  20436. return;
  20437. }
  20438. }
  20439. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20440. return;
  20441. }
  20442. if (!_this.pointerMovePredicate) {
  20443. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20444. }
  20445. // Meshes
  20446. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20447. _this._processPointerMove(pickResult, evt);
  20448. };
  20449. this._onPointerDown = function (evt) {
  20450. _this._totalPointersPressed++;
  20451. _this._pickedDownMesh = null;
  20452. _this._meshPickProceed = false;
  20453. _this._updatePointerPosition(evt);
  20454. if (_this.preventDefaultOnPointerDown && canvas) {
  20455. evt.preventDefault();
  20456. canvas.focus();
  20457. }
  20458. // PreObservable support
  20459. if (_this.onPrePointerObservable.hasObservers()) {
  20460. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20461. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20462. _this.onPrePointerObservable.notifyObservers(pi, type);
  20463. if (pi.skipOnPointerObservable) {
  20464. return;
  20465. }
  20466. }
  20467. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20468. return;
  20469. }
  20470. _this._startingPointerPosition.x = _this._pointerX;
  20471. _this._startingPointerPosition.y = _this._pointerY;
  20472. _this._startingPointerTime = new Date().getTime();
  20473. if (!_this.pointerDownPredicate) {
  20474. _this.pointerDownPredicate = function (mesh) {
  20475. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20476. };
  20477. }
  20478. // Meshes
  20479. _this._pickedDownMesh = null;
  20480. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20481. _this._processPointerDown(pickResult, evt);
  20482. // Sprites
  20483. _this._pickedDownSprite = null;
  20484. if (_this.spriteManagers.length > 0) {
  20485. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20486. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20487. if (pickResult.pickedSprite.actionManager) {
  20488. _this._pickedDownSprite = pickResult.pickedSprite;
  20489. switch (evt.button) {
  20490. case 0:
  20491. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20492. break;
  20493. case 1:
  20494. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20495. break;
  20496. case 2:
  20497. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20498. break;
  20499. }
  20500. if (pickResult.pickedSprite.actionManager) {
  20501. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20502. }
  20503. }
  20504. }
  20505. }
  20506. };
  20507. this._onPointerUp = function (evt) {
  20508. if (_this._totalPointersPressed === 0) {
  20509. return; // So we need to test it the pointer down was pressed before.
  20510. }
  20511. _this._totalPointersPressed--;
  20512. _this._pickedUpMesh = null;
  20513. _this._meshPickProceed = false;
  20514. _this._updatePointerPosition(evt);
  20515. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  20516. // PreObservable support
  20517. if (_this.onPrePointerObservable.hasObservers()) {
  20518. if (!clickInfo.ignore) {
  20519. if (!clickInfo.hasSwiped) {
  20520. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20521. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20522. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20523. _this.onPrePointerObservable.notifyObservers(pi, type);
  20524. if (pi.skipOnPointerObservable) {
  20525. return;
  20526. }
  20527. }
  20528. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20529. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20530. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20531. _this.onPrePointerObservable.notifyObservers(pi, type);
  20532. if (pi.skipOnPointerObservable) {
  20533. return;
  20534. }
  20535. }
  20536. }
  20537. }
  20538. else {
  20539. var type = BABYLON.PointerEventTypes.POINTERUP;
  20540. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20541. _this.onPrePointerObservable.notifyObservers(pi, type);
  20542. if (pi.skipOnPointerObservable) {
  20543. return;
  20544. }
  20545. }
  20546. }
  20547. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20548. return;
  20549. }
  20550. if (!_this.pointerUpPredicate) {
  20551. _this.pointerUpPredicate = function (mesh) {
  20552. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20553. };
  20554. }
  20555. // Meshes
  20556. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  20557. _this._initActionManager(null, clickInfo);
  20558. }
  20559. if (!pickResult) {
  20560. pickResult = _this._currentPickResult;
  20561. }
  20562. _this._processPointerUp(pickResult, evt, clickInfo);
  20563. // Sprites
  20564. if (_this.spriteManagers.length > 0) {
  20565. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20566. if (spritePickResult) {
  20567. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  20568. if (spritePickResult.pickedSprite.actionManager) {
  20569. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20570. if (spritePickResult.pickedSprite.actionManager) {
  20571. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  20572. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20573. }
  20574. }
  20575. }
  20576. }
  20577. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  20578. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20579. }
  20580. }
  20581. }
  20582. _this._previousPickResult = _this._currentPickResult;
  20583. });
  20584. };
  20585. this._onKeyDown = function (evt) {
  20586. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  20587. if (_this.onPreKeyboardObservable.hasObservers()) {
  20588. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20589. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20590. if (pi.skipOnPointerObservable) {
  20591. return;
  20592. }
  20593. }
  20594. if (_this.onKeyboardObservable.hasObservers()) {
  20595. var pi = new BABYLON.KeyboardInfo(type, evt);
  20596. _this.onKeyboardObservable.notifyObservers(pi, type);
  20597. }
  20598. if (_this.actionManager) {
  20599. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20600. }
  20601. };
  20602. this._onKeyUp = function (evt) {
  20603. var type = BABYLON.KeyboardEventTypes.KEYUP;
  20604. if (_this.onPreKeyboardObservable.hasObservers()) {
  20605. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20606. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20607. if (pi.skipOnPointerObservable) {
  20608. return;
  20609. }
  20610. }
  20611. if (_this.onKeyboardObservable.hasObservers()) {
  20612. var pi = new BABYLON.KeyboardInfo(type, evt);
  20613. _this.onKeyboardObservable.notifyObservers(pi, type);
  20614. }
  20615. if (_this.actionManager) {
  20616. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20617. }
  20618. };
  20619. var engine = this.getEngine();
  20620. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  20621. if (!canvas) {
  20622. return;
  20623. }
  20624. canvas.addEventListener("keydown", _this._onKeyDown, false);
  20625. canvas.addEventListener("keyup", _this._onKeyUp, false);
  20626. });
  20627. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  20628. if (!canvas) {
  20629. return;
  20630. }
  20631. canvas.removeEventListener("keydown", _this._onKeyDown);
  20632. canvas.removeEventListener("keyup", _this._onKeyUp);
  20633. });
  20634. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20635. var canvas = this._engine.getRenderingCanvas();
  20636. if (!canvas) {
  20637. return;
  20638. }
  20639. if (attachMove) {
  20640. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20641. // Wheel
  20642. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20643. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20644. }
  20645. if (attachDown) {
  20646. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20647. }
  20648. if (attachUp) {
  20649. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20650. }
  20651. canvas.tabIndex = 1;
  20652. };
  20653. Scene.prototype.detachControl = function () {
  20654. var engine = this.getEngine();
  20655. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20656. var canvas = engine.getRenderingCanvas();
  20657. if (!canvas) {
  20658. return;
  20659. }
  20660. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20661. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20662. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20663. if (this._onCanvasBlurObserver) {
  20664. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  20665. }
  20666. if (this._onCanvasFocusObserver) {
  20667. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  20668. }
  20669. // Wheel
  20670. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20671. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20672. // Keyboard
  20673. canvas.removeEventListener("keydown", this._onKeyDown);
  20674. canvas.removeEventListener("keyup", this._onKeyUp);
  20675. // Observables
  20676. this.onKeyboardObservable.clear();
  20677. this.onPreKeyboardObservable.clear();
  20678. this.onPointerObservable.clear();
  20679. this.onPrePointerObservable.clear();
  20680. };
  20681. /**
  20682. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  20683. * Delay loaded resources are not taking in account
  20684. * @return true if all required resources are ready
  20685. */
  20686. Scene.prototype.isReady = function () {
  20687. if (this._isDisposed) {
  20688. return false;
  20689. }
  20690. if (this._pendingData.length > 0) {
  20691. return false;
  20692. }
  20693. var index;
  20694. var engine = this.getEngine();
  20695. // Geometries
  20696. for (index = 0; index < this._geometries.length; index++) {
  20697. var geometry = this._geometries[index];
  20698. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20699. return false;
  20700. }
  20701. }
  20702. // Meshes
  20703. for (index = 0; index < this.meshes.length; index++) {
  20704. var mesh = this.meshes[index];
  20705. if (!mesh.isEnabled()) {
  20706. continue;
  20707. }
  20708. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  20709. continue;
  20710. }
  20711. if (!mesh.isReady()) {
  20712. return false;
  20713. }
  20714. // Highlight layers
  20715. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  20716. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  20717. var layer = _a[_i];
  20718. if (!layer.hasMesh(mesh)) {
  20719. continue;
  20720. }
  20721. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  20722. var subMesh = _c[_b];
  20723. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  20724. return false;
  20725. }
  20726. }
  20727. }
  20728. }
  20729. return true;
  20730. };
  20731. Scene.prototype.resetCachedMaterial = function () {
  20732. this._cachedMaterial = null;
  20733. this._cachedEffect = null;
  20734. this._cachedVisibility = null;
  20735. };
  20736. Scene.prototype.registerBeforeRender = function (func) {
  20737. this.onBeforeRenderObservable.add(func);
  20738. };
  20739. Scene.prototype.unregisterBeforeRender = function (func) {
  20740. this.onBeforeRenderObservable.removeCallback(func);
  20741. };
  20742. Scene.prototype.registerAfterRender = function (func) {
  20743. this.onAfterRenderObservable.add(func);
  20744. };
  20745. Scene.prototype.unregisterAfterRender = function (func) {
  20746. this.onAfterRenderObservable.removeCallback(func);
  20747. };
  20748. Scene.prototype._executeOnceBeforeRender = function (func) {
  20749. var _this = this;
  20750. var execFunc = function () {
  20751. func();
  20752. setTimeout(function () {
  20753. _this.unregisterBeforeRender(execFunc);
  20754. });
  20755. };
  20756. this.registerBeforeRender(execFunc);
  20757. };
  20758. /**
  20759. * The provided function will run before render once and will be disposed afterwards.
  20760. * A timeout delay can be provided so that the function will be executed in N ms.
  20761. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  20762. * @param func The function to be executed.
  20763. * @param timeout optional delay in ms
  20764. */
  20765. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  20766. var _this = this;
  20767. if (timeout !== undefined) {
  20768. setTimeout(function () {
  20769. _this._executeOnceBeforeRender(func);
  20770. }, timeout);
  20771. }
  20772. else {
  20773. this._executeOnceBeforeRender(func);
  20774. }
  20775. };
  20776. Scene.prototype._addPendingData = function (data) {
  20777. this._pendingData.push(data);
  20778. };
  20779. Scene.prototype._removePendingData = function (data) {
  20780. var wasLoading = this.isLoading;
  20781. var index = this._pendingData.indexOf(data);
  20782. if (index !== -1) {
  20783. this._pendingData.splice(index, 1);
  20784. }
  20785. if (wasLoading && !this.isLoading) {
  20786. this.onDataLoadedObservable.notifyObservers(this);
  20787. }
  20788. };
  20789. Scene.prototype.getWaitingItemsCount = function () {
  20790. return this._pendingData.length;
  20791. };
  20792. Object.defineProperty(Scene.prototype, "isLoading", {
  20793. get: function () {
  20794. return this._pendingData.length > 0;
  20795. },
  20796. enumerable: true,
  20797. configurable: true
  20798. });
  20799. /**
  20800. * Registers a function to be executed when the scene is ready.
  20801. * @param {Function} func - the function to be executed.
  20802. */
  20803. Scene.prototype.executeWhenReady = function (func) {
  20804. var _this = this;
  20805. this.onReadyObservable.add(func);
  20806. if (this._executeWhenReadyTimeoutId !== -1) {
  20807. return;
  20808. }
  20809. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20810. _this._checkIsReady();
  20811. }, 150);
  20812. };
  20813. Scene.prototype._checkIsReady = function () {
  20814. var _this = this;
  20815. if (this.isReady()) {
  20816. this.onReadyObservable.notifyObservers(this);
  20817. this.onReadyObservable.clear();
  20818. this._executeWhenReadyTimeoutId = -1;
  20819. return;
  20820. }
  20821. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20822. _this._checkIsReady();
  20823. }, 150);
  20824. };
  20825. // Animations
  20826. /**
  20827. * Will start the animation sequence of a given target
  20828. * @param target - the target
  20829. * @param {number} from - from which frame should animation start
  20830. * @param {number} to - till which frame should animation run.
  20831. * @param {boolean} [loop] - should the animation loop
  20832. * @param {number} [speedRatio] - the speed in which to run the animation
  20833. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20834. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20835. * Returns {BABYLON.Animatable} the animatable object created for this animation
  20836. * See BABYLON.Animatable
  20837. */
  20838. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20839. if (speedRatio === void 0) { speedRatio = 1.0; }
  20840. if (from > to && speedRatio > 0) {
  20841. speedRatio *= -1;
  20842. }
  20843. this.stopAnimation(target);
  20844. if (!animatable) {
  20845. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20846. }
  20847. // Local animations
  20848. if (target.animations) {
  20849. animatable.appendAnimations(target, target.animations);
  20850. }
  20851. // Children animations
  20852. if (target.getAnimatables) {
  20853. var animatables = target.getAnimatables();
  20854. for (var index = 0; index < animatables.length; index++) {
  20855. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20856. }
  20857. }
  20858. animatable.reset();
  20859. return animatable;
  20860. };
  20861. /**
  20862. * Begin a new animation on a given node
  20863. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20864. * @param {BABYLON.Animation[]} defines the list of animations to start
  20865. * @param {number} from defines the initial value
  20866. * @param {number} to defines the final value
  20867. * @param {boolean} loop defines if you want animation to loop (off by default)
  20868. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20869. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20870. * @returns the list of created animatables
  20871. */
  20872. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20873. if (speedRatio === undefined) {
  20874. speedRatio = 1.0;
  20875. }
  20876. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20877. return animatable;
  20878. };
  20879. /**
  20880. * Begin a new animation on a given node and its hierarchy
  20881. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20882. * @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.
  20883. * @param {BABYLON.Animation[]} defines the list of animations to start
  20884. * @param {number} from defines the initial value
  20885. * @param {number} to defines the final value
  20886. * @param {boolean} loop defines if you want animation to loop (off by default)
  20887. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20888. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20889. * @returns the list of animatables created for all nodes
  20890. */
  20891. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20892. var children = target.getDescendants(directDescendantsOnly);
  20893. var result = [];
  20894. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  20895. var child = children_1[_i];
  20896. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  20897. }
  20898. return result;
  20899. };
  20900. Scene.prototype.getAnimatableByTarget = function (target) {
  20901. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20902. if (this._activeAnimatables[index].target === target) {
  20903. return this._activeAnimatables[index];
  20904. }
  20905. }
  20906. return null;
  20907. };
  20908. Object.defineProperty(Scene.prototype, "animatables", {
  20909. get: function () {
  20910. return this._activeAnimatables;
  20911. },
  20912. enumerable: true,
  20913. configurable: true
  20914. });
  20915. /**
  20916. * Will stop the animation of the given target
  20917. * @param target - the target
  20918. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20919. * @see beginAnimation
  20920. */
  20921. Scene.prototype.stopAnimation = function (target, animationName) {
  20922. var animatable = this.getAnimatableByTarget(target);
  20923. if (animatable) {
  20924. animatable.stop(animationName);
  20925. }
  20926. };
  20927. /**
  20928. * Stops and removes all animations that have been applied to the scene
  20929. */
  20930. Scene.prototype.stopAllAnimations = function () {
  20931. if (this._activeAnimatables) {
  20932. for (var i = 0; i < this._activeAnimatables.length; i++) {
  20933. this._activeAnimatables[i].stop();
  20934. }
  20935. this._activeAnimatables = [];
  20936. }
  20937. };
  20938. Scene.prototype._animate = function () {
  20939. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20940. return;
  20941. }
  20942. // Getting time
  20943. var now = BABYLON.Tools.Now;
  20944. if (!this._animationTimeLast) {
  20945. if (this._pendingData.length > 0) {
  20946. return;
  20947. }
  20948. this._animationTimeLast = now;
  20949. }
  20950. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  20951. this._animationTime += deltaTime;
  20952. this._animationTimeLast = now;
  20953. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20954. this._activeAnimatables[index]._animate(this._animationTime);
  20955. }
  20956. };
  20957. // Matrix
  20958. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  20959. this._useAlternateCameraConfiguration = active;
  20960. };
  20961. Scene.prototype.getViewMatrix = function () {
  20962. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  20963. };
  20964. Scene.prototype.getProjectionMatrix = function () {
  20965. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  20966. };
  20967. Scene.prototype.getTransformMatrix = function () {
  20968. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  20969. };
  20970. Scene.prototype.setTransformMatrix = function (view, projection) {
  20971. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  20972. return;
  20973. }
  20974. this._viewUpdateFlag = view.updateFlag;
  20975. this._projectionUpdateFlag = projection.updateFlag;
  20976. this._viewMatrix = view;
  20977. this._projectionMatrix = projection;
  20978. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20979. // Update frustum
  20980. if (!this._frustumPlanes) {
  20981. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20982. }
  20983. else {
  20984. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20985. }
  20986. if (this.activeCamera && this.activeCamera._alternateCamera) {
  20987. var otherCamera = this.activeCamera._alternateCamera;
  20988. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  20989. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  20990. }
  20991. if (this._sceneUbo.useUbo) {
  20992. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  20993. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  20994. this._sceneUbo.update();
  20995. }
  20996. };
  20997. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  20998. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  20999. return;
  21000. }
  21001. this._alternateViewUpdateFlag = view.updateFlag;
  21002. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21003. this._alternateViewMatrix = view;
  21004. this._alternateProjectionMatrix = projection;
  21005. if (!this._alternateTransformMatrix) {
  21006. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21007. }
  21008. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21009. if (!this._alternateSceneUbo) {
  21010. this._createAlternateUbo();
  21011. }
  21012. if (this._alternateSceneUbo.useUbo) {
  21013. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21014. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21015. this._alternateSceneUbo.update();
  21016. }
  21017. };
  21018. Scene.prototype.getSceneUniformBuffer = function () {
  21019. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21020. };
  21021. // Methods
  21022. Scene.prototype.getUniqueId = function () {
  21023. var result = Scene._uniqueIdCounter;
  21024. Scene._uniqueIdCounter++;
  21025. return result;
  21026. };
  21027. Scene.prototype.addMesh = function (newMesh) {
  21028. this.meshes.push(newMesh);
  21029. //notify the collision coordinator
  21030. if (this.collisionCoordinator) {
  21031. this.collisionCoordinator.onMeshAdded(newMesh);
  21032. }
  21033. newMesh._resyncLightSources();
  21034. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21035. };
  21036. Scene.prototype.removeMesh = function (toRemove) {
  21037. var index = this.meshes.indexOf(toRemove);
  21038. if (index !== -1) {
  21039. // Remove from the scene if mesh found
  21040. this.meshes.splice(index, 1);
  21041. }
  21042. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21043. return index;
  21044. };
  21045. Scene.prototype.addTransformNode = function (newTransformNode) {
  21046. this.transformNodes.push(newTransformNode);
  21047. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21048. };
  21049. Scene.prototype.removeTransformNode = function (toRemove) {
  21050. var index = this.transformNodes.indexOf(toRemove);
  21051. if (index !== -1) {
  21052. // Remove from the scene if found
  21053. this.transformNodes.splice(index, 1);
  21054. }
  21055. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21056. return index;
  21057. };
  21058. Scene.prototype.removeSkeleton = function (toRemove) {
  21059. var index = this.skeletons.indexOf(toRemove);
  21060. if (index !== -1) {
  21061. // Remove from the scene if found
  21062. this.skeletons.splice(index, 1);
  21063. }
  21064. return index;
  21065. };
  21066. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21067. var index = this.morphTargetManagers.indexOf(toRemove);
  21068. if (index !== -1) {
  21069. // Remove from the scene if found
  21070. this.morphTargetManagers.splice(index, 1);
  21071. }
  21072. return index;
  21073. };
  21074. Scene.prototype.removeLight = function (toRemove) {
  21075. var index = this.lights.indexOf(toRemove);
  21076. if (index !== -1) {
  21077. // Remove from meshes
  21078. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21079. var mesh = _a[_i];
  21080. mesh._removeLightSource(toRemove);
  21081. }
  21082. // Remove from the scene if mesh found
  21083. this.lights.splice(index, 1);
  21084. this.sortLightsByPriority();
  21085. }
  21086. this.onLightRemovedObservable.notifyObservers(toRemove);
  21087. return index;
  21088. };
  21089. Scene.prototype.removeCamera = function (toRemove) {
  21090. var index = this.cameras.indexOf(toRemove);
  21091. if (index !== -1) {
  21092. // Remove from the scene if mesh found
  21093. this.cameras.splice(index, 1);
  21094. }
  21095. // Remove from activeCameras
  21096. var index2 = this.activeCameras.indexOf(toRemove);
  21097. if (index2 !== -1) {
  21098. // Remove from the scene if mesh found
  21099. this.activeCameras.splice(index2, 1);
  21100. }
  21101. // Reset the activeCamera
  21102. if (this.activeCamera === toRemove) {
  21103. if (this.cameras.length > 0) {
  21104. this.activeCamera = this.cameras[0];
  21105. }
  21106. else {
  21107. this.activeCamera = null;
  21108. }
  21109. }
  21110. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21111. return index;
  21112. };
  21113. Scene.prototype.removeParticleSystem = function (toRemove) {
  21114. var index = this.particleSystems.indexOf(toRemove);
  21115. if (index !== -1) {
  21116. this.particleSystems.splice(index, 1);
  21117. }
  21118. return index;
  21119. };
  21120. ;
  21121. Scene.prototype.removeAnimation = function (toRemove) {
  21122. var index = this.animations.indexOf(toRemove);
  21123. if (index !== -1) {
  21124. this.animations.splice(index, 1);
  21125. }
  21126. return index;
  21127. };
  21128. ;
  21129. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21130. var index = this.multiMaterials.indexOf(toRemove);
  21131. if (index !== -1) {
  21132. this.multiMaterials.splice(index, 1);
  21133. }
  21134. return index;
  21135. };
  21136. ;
  21137. Scene.prototype.removeMaterial = function (toRemove) {
  21138. var index = this.materials.indexOf(toRemove);
  21139. if (index !== -1) {
  21140. this.materials.splice(index, 1);
  21141. }
  21142. return index;
  21143. };
  21144. ;
  21145. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21146. var index = this.lensFlareSystems.indexOf(toRemove);
  21147. if (index !== -1) {
  21148. this.lensFlareSystems.splice(index, 1);
  21149. }
  21150. return index;
  21151. };
  21152. ;
  21153. Scene.prototype.removeActionManager = function (toRemove) {
  21154. var index = this._actionManagers.indexOf(toRemove);
  21155. if (index !== -1) {
  21156. this._actionManagers.splice(index, 1);
  21157. }
  21158. return index;
  21159. };
  21160. ;
  21161. Scene.prototype.addLight = function (newLight) {
  21162. this.lights.push(newLight);
  21163. this.sortLightsByPriority();
  21164. // Add light to all meshes (To support if the light is removed and then readded)
  21165. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21166. var mesh = _a[_i];
  21167. if (mesh._lightSources.indexOf(newLight) === -1) {
  21168. mesh._lightSources.push(newLight);
  21169. mesh._resyncLightSources();
  21170. }
  21171. }
  21172. this.onNewLightAddedObservable.notifyObservers(newLight);
  21173. };
  21174. Scene.prototype.sortLightsByPriority = function () {
  21175. if (this.requireLightSorting) {
  21176. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21177. }
  21178. };
  21179. Scene.prototype.addCamera = function (newCamera) {
  21180. this.cameras.push(newCamera);
  21181. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21182. };
  21183. Scene.prototype.addSkeleton = function (newSkeleton) {
  21184. this.skeletons.push(newSkeleton);
  21185. };
  21186. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21187. this.particleSystems.push(newParticleSystem);
  21188. };
  21189. Scene.prototype.addAnimation = function (newAnimation) {
  21190. this.animations.push(newAnimation);
  21191. };
  21192. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21193. this.multiMaterials.push(newMultiMaterial);
  21194. };
  21195. Scene.prototype.addMaterial = function (newMaterial) {
  21196. this.materials.push(newMaterial);
  21197. };
  21198. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21199. this.morphTargetManagers.push(newMorphTargetManager);
  21200. };
  21201. Scene.prototype.addGeometry = function (newGeometrie) {
  21202. this._geometries.push(newGeometrie);
  21203. };
  21204. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21205. this.lensFlareSystems.push(newLensFlareSystem);
  21206. };
  21207. Scene.prototype.addActionManager = function (newActionManager) {
  21208. this._actionManagers.push(newActionManager);
  21209. };
  21210. /**
  21211. * Switch active camera
  21212. * @param {Camera} newCamera - new active camera
  21213. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21214. */
  21215. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21216. if (attachControl === void 0) { attachControl = true; }
  21217. var canvas = this._engine.getRenderingCanvas();
  21218. if (!canvas) {
  21219. return;
  21220. }
  21221. if (this.activeCamera) {
  21222. this.activeCamera.detachControl(canvas);
  21223. }
  21224. this.activeCamera = newCamera;
  21225. if (attachControl) {
  21226. newCamera.attachControl(canvas);
  21227. }
  21228. };
  21229. /**
  21230. * sets the active camera of the scene using its ID
  21231. * @param {string} id - the camera's ID
  21232. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21233. * @see activeCamera
  21234. */
  21235. Scene.prototype.setActiveCameraByID = function (id) {
  21236. var camera = this.getCameraByID(id);
  21237. if (camera) {
  21238. this.activeCamera = camera;
  21239. return camera;
  21240. }
  21241. return null;
  21242. };
  21243. /**
  21244. * sets the active camera of the scene using its name
  21245. * @param {string} name - the camera's name
  21246. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21247. * @see activeCamera
  21248. */
  21249. Scene.prototype.setActiveCameraByName = function (name) {
  21250. var camera = this.getCameraByName(name);
  21251. if (camera) {
  21252. this.activeCamera = camera;
  21253. return camera;
  21254. }
  21255. return null;
  21256. };
  21257. /**
  21258. * get an animation group using its name
  21259. * @param {string} the material's name
  21260. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21261. */
  21262. Scene.prototype.getAnimationGroupByName = function (name) {
  21263. for (var index = 0; index < this.animationGroups.length; index++) {
  21264. if (this.animationGroups[index].name === name) {
  21265. return this.animationGroups[index];
  21266. }
  21267. }
  21268. return null;
  21269. };
  21270. /**
  21271. * get a material using its id
  21272. * @param {string} the material's ID
  21273. * @return {BABYLON.Material|null} the material or null if none found.
  21274. */
  21275. Scene.prototype.getMaterialByID = function (id) {
  21276. for (var index = 0; index < this.materials.length; index++) {
  21277. if (this.materials[index].id === id) {
  21278. return this.materials[index];
  21279. }
  21280. }
  21281. return null;
  21282. };
  21283. /**
  21284. * get a material using its name
  21285. * @param {string} the material's name
  21286. * @return {BABYLON.Material|null} the material or null if none found.
  21287. */
  21288. Scene.prototype.getMaterialByName = function (name) {
  21289. for (var index = 0; index < this.materials.length; index++) {
  21290. if (this.materials[index].name === name) {
  21291. return this.materials[index];
  21292. }
  21293. }
  21294. return null;
  21295. };
  21296. Scene.prototype.getLensFlareSystemByName = function (name) {
  21297. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21298. if (this.lensFlareSystems[index].name === name) {
  21299. return this.lensFlareSystems[index];
  21300. }
  21301. }
  21302. return null;
  21303. };
  21304. Scene.prototype.getLensFlareSystemByID = function (id) {
  21305. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21306. if (this.lensFlareSystems[index].id === id) {
  21307. return this.lensFlareSystems[index];
  21308. }
  21309. }
  21310. return null;
  21311. };
  21312. Scene.prototype.getCameraByID = function (id) {
  21313. for (var index = 0; index < this.cameras.length; index++) {
  21314. if (this.cameras[index].id === id) {
  21315. return this.cameras[index];
  21316. }
  21317. }
  21318. return null;
  21319. };
  21320. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21321. for (var index = 0; index < this.cameras.length; index++) {
  21322. if (this.cameras[index].uniqueId === uniqueId) {
  21323. return this.cameras[index];
  21324. }
  21325. }
  21326. return null;
  21327. };
  21328. /**
  21329. * get a camera using its name
  21330. * @param {string} the camera's name
  21331. * @return {BABYLON.Camera|null} the camera or null if none found.
  21332. */
  21333. Scene.prototype.getCameraByName = function (name) {
  21334. for (var index = 0; index < this.cameras.length; index++) {
  21335. if (this.cameras[index].name === name) {
  21336. return this.cameras[index];
  21337. }
  21338. }
  21339. return null;
  21340. };
  21341. /**
  21342. * get a bone using its id
  21343. * @param {string} the bone's id
  21344. * @return {BABYLON.Bone|null} the bone or null if not found
  21345. */
  21346. Scene.prototype.getBoneByID = function (id) {
  21347. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21348. var skeleton = this.skeletons[skeletonIndex];
  21349. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21350. if (skeleton.bones[boneIndex].id === id) {
  21351. return skeleton.bones[boneIndex];
  21352. }
  21353. }
  21354. }
  21355. return null;
  21356. };
  21357. /**
  21358. * get a bone using its id
  21359. * @param {string} the bone's name
  21360. * @return {BABYLON.Bone|null} the bone or null if not found
  21361. */
  21362. Scene.prototype.getBoneByName = function (name) {
  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].name === name) {
  21367. return skeleton.bones[boneIndex];
  21368. }
  21369. }
  21370. }
  21371. return null;
  21372. };
  21373. /**
  21374. * get a light node using its name
  21375. * @param {string} the light's name
  21376. * @return {BABYLON.Light|null} the light or null if none found.
  21377. */
  21378. Scene.prototype.getLightByName = function (name) {
  21379. for (var index = 0; index < this.lights.length; index++) {
  21380. if (this.lights[index].name === name) {
  21381. return this.lights[index];
  21382. }
  21383. }
  21384. return null;
  21385. };
  21386. /**
  21387. * get a light node using its ID
  21388. * @param {string} the light's id
  21389. * @return {BABYLON.Light|null} the light or null if none found.
  21390. */
  21391. Scene.prototype.getLightByID = function (id) {
  21392. for (var index = 0; index < this.lights.length; index++) {
  21393. if (this.lights[index].id === id) {
  21394. return this.lights[index];
  21395. }
  21396. }
  21397. return null;
  21398. };
  21399. /**
  21400. * get a light node using its scene-generated unique ID
  21401. * @param {number} the light's unique id
  21402. * @return {BABYLON.Light|null} the light or null if none found.
  21403. */
  21404. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21405. for (var index = 0; index < this.lights.length; index++) {
  21406. if (this.lights[index].uniqueId === uniqueId) {
  21407. return this.lights[index];
  21408. }
  21409. }
  21410. return null;
  21411. };
  21412. /**
  21413. * get a particle system by id
  21414. * @param id {number} the particle system id
  21415. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  21416. */
  21417. Scene.prototype.getParticleSystemByID = function (id) {
  21418. for (var index = 0; index < this.particleSystems.length; index++) {
  21419. if (this.particleSystems[index].id === id) {
  21420. return this.particleSystems[index];
  21421. }
  21422. }
  21423. return null;
  21424. };
  21425. /**
  21426. * get a geometry using its ID
  21427. * @param {string} the geometry's id
  21428. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21429. */
  21430. Scene.prototype.getGeometryByID = function (id) {
  21431. for (var index = 0; index < this._geometries.length; index++) {
  21432. if (this._geometries[index].id === id) {
  21433. return this._geometries[index];
  21434. }
  21435. }
  21436. return null;
  21437. };
  21438. /**
  21439. * add a new geometry to this scene.
  21440. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21441. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21442. * @return {boolean} was the geometry added or not
  21443. */
  21444. Scene.prototype.pushGeometry = function (geometry, force) {
  21445. if (!force && this.getGeometryByID(geometry.id)) {
  21446. return false;
  21447. }
  21448. this._geometries.push(geometry);
  21449. //notify the collision coordinator
  21450. if (this.collisionCoordinator) {
  21451. this.collisionCoordinator.onGeometryAdded(geometry);
  21452. }
  21453. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21454. return true;
  21455. };
  21456. /**
  21457. * Removes an existing geometry
  21458. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21459. * @return {boolean} was the geometry removed or not
  21460. */
  21461. Scene.prototype.removeGeometry = function (geometry) {
  21462. var index = this._geometries.indexOf(geometry);
  21463. if (index > -1) {
  21464. this._geometries.splice(index, 1);
  21465. //notify the collision coordinator
  21466. if (this.collisionCoordinator) {
  21467. this.collisionCoordinator.onGeometryDeleted(geometry);
  21468. }
  21469. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21470. return true;
  21471. }
  21472. return false;
  21473. };
  21474. Scene.prototype.getGeometries = function () {
  21475. return this._geometries;
  21476. };
  21477. /**
  21478. * Get the first added mesh found of a given ID
  21479. * @param {string} id - the id to search for
  21480. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21481. */
  21482. Scene.prototype.getMeshByID = function (id) {
  21483. for (var index = 0; index < this.meshes.length; index++) {
  21484. if (this.meshes[index].id === id) {
  21485. return this.meshes[index];
  21486. }
  21487. }
  21488. return null;
  21489. };
  21490. Scene.prototype.getMeshesByID = function (id) {
  21491. return this.meshes.filter(function (m) {
  21492. return m.id === id;
  21493. });
  21494. };
  21495. /**
  21496. * Get the first added transform node found of a given ID
  21497. * @param {string} id - the id to search for
  21498. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  21499. */
  21500. Scene.prototype.getTransformNodeByID = function (id) {
  21501. for (var index = 0; index < this.transformNodes.length; index++) {
  21502. if (this.transformNodes[index].id === id) {
  21503. return this.transformNodes[index];
  21504. }
  21505. }
  21506. return null;
  21507. };
  21508. Scene.prototype.getTransformNodesByID = function (id) {
  21509. return this.transformNodes.filter(function (m) {
  21510. return m.id === id;
  21511. });
  21512. };
  21513. /**
  21514. * Get a mesh with its auto-generated unique id
  21515. * @param {number} uniqueId - the unique id to search for
  21516. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21517. */
  21518. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21519. for (var index = 0; index < this.meshes.length; index++) {
  21520. if (this.meshes[index].uniqueId === uniqueId) {
  21521. return this.meshes[index];
  21522. }
  21523. }
  21524. return null;
  21525. };
  21526. /**
  21527. * Get a the last added mesh found of a given ID
  21528. * @param {string} id - the id to search for
  21529. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21530. */
  21531. Scene.prototype.getLastMeshByID = function (id) {
  21532. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21533. if (this.meshes[index].id === id) {
  21534. return this.meshes[index];
  21535. }
  21536. }
  21537. return null;
  21538. };
  21539. /**
  21540. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21541. * @param {string} id - the id to search for
  21542. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21543. */
  21544. Scene.prototype.getLastEntryByID = function (id) {
  21545. var index;
  21546. for (index = this.meshes.length - 1; index >= 0; index--) {
  21547. if (this.meshes[index].id === id) {
  21548. return this.meshes[index];
  21549. }
  21550. }
  21551. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  21552. if (this.transformNodes[index].id === id) {
  21553. return this.transformNodes[index];
  21554. }
  21555. }
  21556. for (index = this.cameras.length - 1; index >= 0; index--) {
  21557. if (this.cameras[index].id === id) {
  21558. return this.cameras[index];
  21559. }
  21560. }
  21561. for (index = this.lights.length - 1; index >= 0; index--) {
  21562. if (this.lights[index].id === id) {
  21563. return this.lights[index];
  21564. }
  21565. }
  21566. return null;
  21567. };
  21568. Scene.prototype.getNodeByID = function (id) {
  21569. var mesh = this.getMeshByID(id);
  21570. if (mesh) {
  21571. return mesh;
  21572. }
  21573. var light = this.getLightByID(id);
  21574. if (light) {
  21575. return light;
  21576. }
  21577. var camera = this.getCameraByID(id);
  21578. if (camera) {
  21579. return camera;
  21580. }
  21581. var bone = this.getBoneByID(id);
  21582. return bone;
  21583. };
  21584. Scene.prototype.getNodeByName = function (name) {
  21585. var mesh = this.getMeshByName(name);
  21586. if (mesh) {
  21587. return mesh;
  21588. }
  21589. var light = this.getLightByName(name);
  21590. if (light) {
  21591. return light;
  21592. }
  21593. var camera = this.getCameraByName(name);
  21594. if (camera) {
  21595. return camera;
  21596. }
  21597. var bone = this.getBoneByName(name);
  21598. return bone;
  21599. };
  21600. Scene.prototype.getMeshByName = function (name) {
  21601. for (var index = 0; index < this.meshes.length; index++) {
  21602. if (this.meshes[index].name === name) {
  21603. return this.meshes[index];
  21604. }
  21605. }
  21606. return null;
  21607. };
  21608. Scene.prototype.getTransformNodeByName = function (name) {
  21609. for (var index = 0; index < this.transformNodes.length; index++) {
  21610. if (this.transformNodes[index].name === name) {
  21611. return this.transformNodes[index];
  21612. }
  21613. }
  21614. return null;
  21615. };
  21616. Scene.prototype.getSoundByName = function (name) {
  21617. var index;
  21618. if (BABYLON.AudioEngine) {
  21619. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21620. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21621. return this.mainSoundTrack.soundCollection[index];
  21622. }
  21623. }
  21624. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21625. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21626. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21627. return this.soundTracks[sdIndex].soundCollection[index];
  21628. }
  21629. }
  21630. }
  21631. }
  21632. return null;
  21633. };
  21634. Scene.prototype.getLastSkeletonByID = function (id) {
  21635. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21636. if (this.skeletons[index].id === id) {
  21637. return this.skeletons[index];
  21638. }
  21639. }
  21640. return null;
  21641. };
  21642. Scene.prototype.getSkeletonById = function (id) {
  21643. for (var index = 0; index < this.skeletons.length; index++) {
  21644. if (this.skeletons[index].id === id) {
  21645. return this.skeletons[index];
  21646. }
  21647. }
  21648. return null;
  21649. };
  21650. Scene.prototype.getSkeletonByName = function (name) {
  21651. for (var index = 0; index < this.skeletons.length; index++) {
  21652. if (this.skeletons[index].name === name) {
  21653. return this.skeletons[index];
  21654. }
  21655. }
  21656. return null;
  21657. };
  21658. Scene.prototype.getMorphTargetManagerById = function (id) {
  21659. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  21660. if (this.morphTargetManagers[index].uniqueId === id) {
  21661. return this.morphTargetManagers[index];
  21662. }
  21663. }
  21664. return null;
  21665. };
  21666. Scene.prototype.isActiveMesh = function (mesh) {
  21667. return (this._activeMeshes.indexOf(mesh) !== -1);
  21668. };
  21669. /**
  21670. * Return a the first highlight layer of the scene with a given name.
  21671. * @param name The name of the highlight layer to look for.
  21672. * @return The highlight layer if found otherwise null.
  21673. */
  21674. Scene.prototype.getHighlightLayerByName = function (name) {
  21675. for (var index = 0; index < this.highlightLayers.length; index++) {
  21676. if (this.highlightLayers[index].name === name) {
  21677. return this.highlightLayers[index];
  21678. }
  21679. }
  21680. return null;
  21681. };
  21682. Object.defineProperty(Scene.prototype, "uid", {
  21683. /**
  21684. * Return a unique id as a string which can serve as an identifier for the scene
  21685. */
  21686. get: function () {
  21687. if (!this._uid) {
  21688. this._uid = BABYLON.Tools.RandomId();
  21689. }
  21690. return this._uid;
  21691. },
  21692. enumerable: true,
  21693. configurable: true
  21694. });
  21695. /**
  21696. * Add an externaly attached data from its key.
  21697. * This method call will fail and return false, if such key already exists.
  21698. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21699. * @param key the unique key that identifies the data
  21700. * @param data the data object to associate to the key for this Engine instance
  21701. * @return true if no such key were already present and the data was added successfully, false otherwise
  21702. */
  21703. Scene.prototype.addExternalData = function (key, data) {
  21704. if (!this._externalData) {
  21705. this._externalData = new BABYLON.StringDictionary();
  21706. }
  21707. return this._externalData.add(key, data);
  21708. };
  21709. /**
  21710. * Get an externaly attached data from its key
  21711. * @param key the unique key that identifies the data
  21712. * @return the associated data, if present (can be null), or undefined if not present
  21713. */
  21714. Scene.prototype.getExternalData = function (key) {
  21715. if (!this._externalData) {
  21716. return null;
  21717. }
  21718. return this._externalData.get(key);
  21719. };
  21720. /**
  21721. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21722. * @param key the unique key that identifies the data
  21723. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21724. * @return the associated data, can be null if the factory returned null.
  21725. */
  21726. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21727. if (!this._externalData) {
  21728. this._externalData = new BABYLON.StringDictionary();
  21729. }
  21730. return this._externalData.getOrAddWithFactory(key, factory);
  21731. };
  21732. /**
  21733. * Remove an externaly attached data from the Engine instance
  21734. * @param key the unique key that identifies the data
  21735. * @return true if the data was successfully removed, false if it doesn't exist
  21736. */
  21737. Scene.prototype.removeExternalData = function (key) {
  21738. return this._externalData.remove(key);
  21739. };
  21740. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21741. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21742. if (mesh.showSubMeshesBoundingBox) {
  21743. var boundingInfo = subMesh.getBoundingInfo();
  21744. if (boundingInfo !== null && boundingInfo !== undefined) {
  21745. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21746. }
  21747. }
  21748. var material = subMesh.getMaterial();
  21749. if (material !== null && material !== undefined) {
  21750. // Render targets
  21751. if (material.getRenderTargetTextures !== undefined) {
  21752. if (this._processedMaterials.indexOf(material) === -1) {
  21753. this._processedMaterials.push(material);
  21754. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21755. }
  21756. }
  21757. // Dispatch
  21758. this._activeIndices.addCount(subMesh.indexCount, false);
  21759. this._renderingManager.dispatch(subMesh, mesh, material);
  21760. }
  21761. }
  21762. };
  21763. Scene.prototype._isInIntermediateRendering = function () {
  21764. return this._intermediateRendering;
  21765. };
  21766. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  21767. this._activeMeshCandidateProvider = provider;
  21768. };
  21769. Scene.prototype.getActiveMeshCandidateProvider = function () {
  21770. return this._activeMeshCandidateProvider;
  21771. };
  21772. /**
  21773. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  21774. */
  21775. Scene.prototype.freezeActiveMeshes = function () {
  21776. this._evaluateActiveMeshes();
  21777. this._activeMeshesFrozen = true;
  21778. return this;
  21779. };
  21780. /**
  21781. * Use this function to restart evaluating active meshes on every frame
  21782. */
  21783. Scene.prototype.unfreezeActiveMeshes = function () {
  21784. this._activeMeshesFrozen = false;
  21785. return this;
  21786. };
  21787. Scene.prototype._evaluateActiveMeshes = function () {
  21788. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  21789. return;
  21790. }
  21791. if (!this.activeCamera) {
  21792. return;
  21793. }
  21794. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  21795. this.activeCamera._activeMeshes.reset();
  21796. this._activeMeshes.reset();
  21797. this._renderingManager.reset();
  21798. this._processedMaterials.reset();
  21799. this._activeParticleSystems.reset();
  21800. this._activeSkeletons.reset();
  21801. this._softwareSkinnedMeshes.reset();
  21802. if (this._boundingBoxRenderer) {
  21803. this._boundingBoxRenderer.reset();
  21804. }
  21805. // Meshes
  21806. var meshes;
  21807. var len;
  21808. var checkIsEnabled = true;
  21809. // Determine mesh candidates
  21810. if (this._activeMeshCandidateProvider !== undefined) {
  21811. // Use _activeMeshCandidateProvider
  21812. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  21813. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  21814. if (meshes !== undefined) {
  21815. len = meshes.length;
  21816. }
  21817. else {
  21818. len = 0;
  21819. }
  21820. }
  21821. else if (this._selectionOctree !== undefined) {
  21822. // Octree
  21823. var selection = this._selectionOctree.select(this._frustumPlanes);
  21824. meshes = selection.data;
  21825. len = selection.length;
  21826. }
  21827. else {
  21828. // Full scene traversal
  21829. len = this.meshes.length;
  21830. meshes = this.meshes;
  21831. }
  21832. // Check each mesh
  21833. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  21834. mesh = meshes[meshIndex];
  21835. if (mesh.isBlocked) {
  21836. continue;
  21837. }
  21838. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21839. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  21840. continue;
  21841. }
  21842. mesh.computeWorldMatrix();
  21843. // Intersections
  21844. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21845. this._meshesForIntersections.pushNoDuplicate(mesh);
  21846. }
  21847. // Switch to current LOD
  21848. meshLOD = mesh.getLOD(this.activeCamera);
  21849. if (meshLOD === undefined || meshLOD === null) {
  21850. continue;
  21851. }
  21852. mesh._preActivate();
  21853. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21854. this._activeMeshes.push(mesh);
  21855. this.activeCamera._activeMeshes.push(mesh);
  21856. mesh._activate(this._renderId);
  21857. if (meshLOD !== mesh) {
  21858. meshLOD._activate(this._renderId);
  21859. }
  21860. this._activeMesh(mesh, meshLOD);
  21861. }
  21862. }
  21863. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  21864. // Particle systems
  21865. if (this.particlesEnabled) {
  21866. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  21867. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21868. var particleSystem = this.particleSystems[particleIndex];
  21869. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  21870. continue;
  21871. }
  21872. var emitter = particleSystem.emitter;
  21873. if (!emitter.position || emitter.isEnabled()) {
  21874. this._activeParticleSystems.push(particleSystem);
  21875. particleSystem.animate();
  21876. this._renderingManager.dispatchParticles(particleSystem);
  21877. }
  21878. }
  21879. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  21880. }
  21881. };
  21882. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21883. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  21884. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21885. mesh.skeleton.prepare();
  21886. }
  21887. if (!mesh.computeBonesUsingShaders) {
  21888. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21889. }
  21890. }
  21891. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21892. var boundingInfo = sourceMesh.getBoundingInfo();
  21893. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21894. }
  21895. if (mesh !== undefined && mesh !== null
  21896. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  21897. // Submeshes Octrees
  21898. var len;
  21899. var subMeshes;
  21900. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  21901. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21902. len = intersections.length;
  21903. subMeshes = intersections.data;
  21904. }
  21905. else {
  21906. subMeshes = mesh.subMeshes;
  21907. len = subMeshes.length;
  21908. }
  21909. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  21910. subMesh = subMeshes[subIndex];
  21911. this._evaluateSubMesh(subMesh, mesh);
  21912. }
  21913. }
  21914. };
  21915. Scene.prototype.updateTransformMatrix = function (force) {
  21916. if (!this.activeCamera) {
  21917. return;
  21918. }
  21919. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21920. };
  21921. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  21922. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  21923. };
  21924. Scene.prototype._renderForCamera = function (camera) {
  21925. if (camera && camera._skipRendering) {
  21926. return;
  21927. }
  21928. var engine = this._engine;
  21929. this.activeCamera = camera;
  21930. if (!this.activeCamera)
  21931. throw new Error("Active camera not set");
  21932. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21933. // Viewport
  21934. engine.setViewport(this.activeCamera.viewport);
  21935. // Camera
  21936. this.resetCachedMaterial();
  21937. this._renderId++;
  21938. this.activeCamera.update();
  21939. this.updateTransformMatrix();
  21940. if (camera._alternateCamera) {
  21941. this.updateAlternateTransformMatrix(camera._alternateCamera);
  21942. this._alternateRendering = true;
  21943. }
  21944. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21945. // Meshes
  21946. this._evaluateActiveMeshes();
  21947. // Software skinning
  21948. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21949. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21950. mesh.applySkeleton(mesh.skeleton);
  21951. }
  21952. // Render targets
  21953. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  21954. var needsRestoreFrameBuffer = false;
  21955. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  21956. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  21957. }
  21958. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  21959. this._intermediateRendering = true;
  21960. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21961. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  21962. var renderTarget = this._renderTargets.data[renderIndex];
  21963. if (renderTarget._shouldRender()) {
  21964. this._renderId++;
  21965. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  21966. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  21967. }
  21968. }
  21969. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21970. this._intermediateRendering = false;
  21971. this._renderId++;
  21972. needsRestoreFrameBuffer = true; // Restore back buffer
  21973. }
  21974. // Render HighlightLayer Texture
  21975. var stencilState = this._engine.getStencilBuffer();
  21976. var renderhighlights = false;
  21977. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  21978. this._intermediateRendering = true;
  21979. for (var i = 0; i < this.highlightLayers.length; i++) {
  21980. var highlightLayer = this.highlightLayers[i];
  21981. if (highlightLayer.shouldRender() &&
  21982. (!highlightLayer.camera ||
  21983. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  21984. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  21985. renderhighlights = true;
  21986. var renderTarget = highlightLayer._mainTexture;
  21987. if (renderTarget._shouldRender()) {
  21988. this._renderId++;
  21989. renderTarget.render(false, false);
  21990. needsRestoreFrameBuffer = true;
  21991. }
  21992. }
  21993. }
  21994. this._intermediateRendering = false;
  21995. this._renderId++;
  21996. }
  21997. if (needsRestoreFrameBuffer) {
  21998. engine.restoreDefaultFramebuffer(); // Restore back buffer
  21999. }
  22000. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22001. // Prepare Frame
  22002. this.postProcessManager._prepareFrame();
  22003. // Backgrounds
  22004. var layerIndex;
  22005. var layer;
  22006. if (this.layers.length) {
  22007. engine.setDepthBuffer(false);
  22008. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22009. layer = this.layers[layerIndex];
  22010. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22011. layer.render();
  22012. }
  22013. }
  22014. engine.setDepthBuffer(true);
  22015. }
  22016. // Activate HighlightLayer stencil
  22017. if (renderhighlights) {
  22018. this._engine.setStencilBuffer(true);
  22019. }
  22020. // Render
  22021. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22022. this._renderingManager.render(null, null, true, true);
  22023. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22024. // Restore HighlightLayer stencil
  22025. if (renderhighlights) {
  22026. this._engine.setStencilBuffer(stencilState);
  22027. }
  22028. // Bounding boxes
  22029. if (this._boundingBoxRenderer) {
  22030. this._boundingBoxRenderer.render();
  22031. }
  22032. // Lens flares
  22033. if (this.lensFlaresEnabled) {
  22034. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22035. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22036. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22037. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22038. lensFlareSystem.render();
  22039. }
  22040. }
  22041. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22042. }
  22043. // Foregrounds
  22044. if (this.layers.length) {
  22045. engine.setDepthBuffer(false);
  22046. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22047. layer = this.layers[layerIndex];
  22048. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22049. layer.render();
  22050. }
  22051. }
  22052. engine.setDepthBuffer(true);
  22053. }
  22054. // Highlight Layer
  22055. if (renderhighlights) {
  22056. engine.setDepthBuffer(false);
  22057. for (var i = 0; i < this.highlightLayers.length; i++) {
  22058. if (this.highlightLayers[i].shouldRender()) {
  22059. this.highlightLayers[i].render();
  22060. }
  22061. }
  22062. engine.setDepthBuffer(true);
  22063. }
  22064. // Finalize frame
  22065. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22066. // Reset some special arrays
  22067. this._renderTargets.reset();
  22068. this._alternateRendering = false;
  22069. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22070. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22071. };
  22072. Scene.prototype._processSubCameras = function (camera) {
  22073. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22074. this._renderForCamera(camera);
  22075. return;
  22076. }
  22077. // Update camera
  22078. if (this.activeCamera) {
  22079. this.activeCamera.update();
  22080. }
  22081. // rig cameras
  22082. for (var index = 0; index < camera._rigCameras.length; index++) {
  22083. this._renderForCamera(camera._rigCameras[index]);
  22084. }
  22085. this.activeCamera = camera;
  22086. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22087. };
  22088. Scene.prototype._checkIntersections = function () {
  22089. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22090. var sourceMesh = this._meshesForIntersections.data[index];
  22091. if (!sourceMesh.actionManager) {
  22092. continue;
  22093. }
  22094. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22095. var action = sourceMesh.actionManager.actions[actionIndex];
  22096. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22097. var parameters = action.getTriggerParameter();
  22098. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22099. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22100. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22101. if (areIntersecting && currentIntersectionInProgress === -1) {
  22102. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22103. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22104. sourceMesh._intersectionsInProgress.push(otherMesh);
  22105. }
  22106. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22107. sourceMesh._intersectionsInProgress.push(otherMesh);
  22108. }
  22109. }
  22110. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22111. //They intersected, and now they don't.
  22112. //is this trigger an exit trigger? execute an event.
  22113. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22114. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22115. }
  22116. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22117. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22118. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22119. }
  22120. }
  22121. }
  22122. }
  22123. }
  22124. };
  22125. Scene.prototype.render = function () {
  22126. if (this.isDisposed) {
  22127. return;
  22128. }
  22129. this._activeParticles.fetchNewFrame();
  22130. this._totalVertices.fetchNewFrame();
  22131. this._activeIndices.fetchNewFrame();
  22132. this._activeBones.fetchNewFrame();
  22133. this._meshesForIntersections.reset();
  22134. this.resetCachedMaterial();
  22135. this.onBeforeAnimationsObservable.notifyObservers(this);
  22136. // Actions
  22137. if (this.actionManager) {
  22138. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22139. }
  22140. //Simplification Queue
  22141. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22142. this.simplificationQueue.executeNext();
  22143. }
  22144. if (this._engine.isDeterministicLockStep()) {
  22145. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22146. var defaultFPS = (60.0 / 1000.0);
  22147. var defaultFrameTime = 1000 / 60; // frame time in MS
  22148. if (this._physicsEngine) {
  22149. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22150. }
  22151. var stepsTaken = 0;
  22152. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22153. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22154. internalSteps = Math.min(internalSteps, maxSubSteps);
  22155. do {
  22156. this.onBeforeStepObservable.notifyObservers(this);
  22157. // Animations
  22158. this._animationRatio = defaultFrameTime * defaultFPS;
  22159. this._animate();
  22160. this.onAfterAnimationsObservable.notifyObservers(this);
  22161. // Physics
  22162. if (this._physicsEngine) {
  22163. this.onBeforePhysicsObservable.notifyObservers(this);
  22164. this._physicsEngine._step(defaultFrameTime / 1000);
  22165. this.onAfterPhysicsObservable.notifyObservers(this);
  22166. }
  22167. this.onAfterStepObservable.notifyObservers(this);
  22168. this._currentStepId++;
  22169. stepsTaken++;
  22170. deltaTime -= defaultFrameTime;
  22171. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22172. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22173. }
  22174. else {
  22175. // Animations
  22176. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22177. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22178. this._animate();
  22179. this.onAfterAnimationsObservable.notifyObservers(this);
  22180. // Physics
  22181. if (this._physicsEngine) {
  22182. this.onBeforePhysicsObservable.notifyObservers(this);
  22183. this._physicsEngine._step(deltaTime / 1000.0);
  22184. this.onAfterPhysicsObservable.notifyObservers(this);
  22185. }
  22186. }
  22187. // update gamepad manager
  22188. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22189. this._gamepadManager._checkGamepadsStatus();
  22190. }
  22191. // Before render
  22192. this.onBeforeRenderObservable.notifyObservers(this);
  22193. // Customs render targets
  22194. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22195. var engine = this.getEngine();
  22196. var currentActiveCamera = this.activeCamera;
  22197. if (this.renderTargetsEnabled) {
  22198. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22199. this._intermediateRendering = true;
  22200. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22201. var renderTarget = this.customRenderTargets[customIndex];
  22202. if (renderTarget._shouldRender()) {
  22203. this._renderId++;
  22204. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22205. if (!this.activeCamera)
  22206. throw new Error("Active camera not set");
  22207. // Viewport
  22208. engine.setViewport(this.activeCamera.viewport);
  22209. // Camera
  22210. this.updateTransformMatrix();
  22211. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22212. }
  22213. }
  22214. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22215. this._intermediateRendering = false;
  22216. this._renderId++;
  22217. }
  22218. // Restore back buffer
  22219. if (this.customRenderTargets.length > 0) {
  22220. engine.restoreDefaultFramebuffer();
  22221. }
  22222. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22223. this.activeCamera = currentActiveCamera;
  22224. // Procedural textures
  22225. if (this.proceduralTexturesEnabled) {
  22226. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22227. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22228. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22229. if (proceduralTexture._shouldRender()) {
  22230. proceduralTexture.render();
  22231. }
  22232. }
  22233. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22234. }
  22235. // Clear
  22236. if (this.autoClearDepthAndStencil || this.autoClear) {
  22237. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22238. }
  22239. // Shadows
  22240. if (this.shadowsEnabled) {
  22241. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22242. var light = this.lights[lightIndex];
  22243. var shadowGenerator = light.getShadowGenerator();
  22244. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22245. var shadowMap = (shadowGenerator.getShadowMap());
  22246. if (this.textures.indexOf(shadowMap) !== -1) {
  22247. this._renderTargets.push(shadowMap);
  22248. }
  22249. }
  22250. }
  22251. }
  22252. // Depth renderer
  22253. if (this._depthRenderer) {
  22254. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22255. }
  22256. // Geometry renderer
  22257. if (this._geometryBufferRenderer) {
  22258. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22259. }
  22260. // RenderPipeline
  22261. if (this._postProcessRenderPipelineManager) {
  22262. this._postProcessRenderPipelineManager.update();
  22263. }
  22264. // Multi-cameras?
  22265. if (this.activeCameras.length > 0) {
  22266. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22267. if (cameraIndex > 0) {
  22268. this._engine.clear(null, false, true, true);
  22269. }
  22270. this._processSubCameras(this.activeCameras[cameraIndex]);
  22271. }
  22272. }
  22273. else {
  22274. if (!this.activeCamera) {
  22275. throw new Error("No camera defined");
  22276. }
  22277. this._processSubCameras(this.activeCamera);
  22278. }
  22279. // Intersection checks
  22280. this._checkIntersections();
  22281. // Update the audio listener attached to the camera
  22282. if (BABYLON.AudioEngine) {
  22283. this._updateAudioParameters();
  22284. }
  22285. // After render
  22286. if (this.afterRender) {
  22287. this.afterRender();
  22288. }
  22289. this.onAfterRenderObservable.notifyObservers(this);
  22290. // Cleaning
  22291. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22292. var data = this._toBeDisposed.data[index];
  22293. if (data) {
  22294. data.dispose();
  22295. }
  22296. this._toBeDisposed[index] = null;
  22297. }
  22298. this._toBeDisposed.reset();
  22299. if (this.dumpNextRenderTargets) {
  22300. this.dumpNextRenderTargets = false;
  22301. }
  22302. this._activeBones.addCount(0, true);
  22303. this._activeIndices.addCount(0, true);
  22304. this._activeParticles.addCount(0, true);
  22305. };
  22306. Scene.prototype._updateAudioParameters = function () {
  22307. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22308. return;
  22309. }
  22310. var listeningCamera;
  22311. var audioEngine = BABYLON.Engine.audioEngine;
  22312. if (this.activeCameras.length > 0) {
  22313. listeningCamera = this.activeCameras[0];
  22314. }
  22315. else {
  22316. listeningCamera = this.activeCamera;
  22317. }
  22318. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22319. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22320. // for VR cameras
  22321. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22322. listeningCamera = listeningCamera.rigCameras[0];
  22323. }
  22324. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22325. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22326. cameraDirection.normalize();
  22327. // To avoid some errors on GearVR
  22328. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22329. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22330. }
  22331. var i;
  22332. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22333. var sound = this.mainSoundTrack.soundCollection[i];
  22334. if (sound.useCustomAttenuation) {
  22335. sound.updateDistanceFromListener();
  22336. }
  22337. }
  22338. for (i = 0; i < this.soundTracks.length; i++) {
  22339. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22340. sound = this.soundTracks[i].soundCollection[j];
  22341. if (sound.useCustomAttenuation) {
  22342. sound.updateDistanceFromListener();
  22343. }
  22344. }
  22345. }
  22346. }
  22347. };
  22348. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22349. // Audio
  22350. get: function () {
  22351. return this._audioEnabled;
  22352. },
  22353. set: function (value) {
  22354. this._audioEnabled = value;
  22355. if (BABYLON.AudioEngine) {
  22356. if (this._audioEnabled) {
  22357. this._enableAudio();
  22358. }
  22359. else {
  22360. this._disableAudio();
  22361. }
  22362. }
  22363. },
  22364. enumerable: true,
  22365. configurable: true
  22366. });
  22367. Scene.prototype._disableAudio = function () {
  22368. var i;
  22369. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22370. this.mainSoundTrack.soundCollection[i].pause();
  22371. }
  22372. for (i = 0; i < this.soundTracks.length; i++) {
  22373. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22374. this.soundTracks[i].soundCollection[j].pause();
  22375. }
  22376. }
  22377. };
  22378. Scene.prototype._enableAudio = function () {
  22379. var i;
  22380. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22381. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22382. this.mainSoundTrack.soundCollection[i].play();
  22383. }
  22384. }
  22385. for (i = 0; i < this.soundTracks.length; i++) {
  22386. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22387. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22388. this.soundTracks[i].soundCollection[j].play();
  22389. }
  22390. }
  22391. }
  22392. };
  22393. Object.defineProperty(Scene.prototype, "headphone", {
  22394. get: function () {
  22395. return this._headphone;
  22396. },
  22397. set: function (value) {
  22398. this._headphone = value;
  22399. if (BABYLON.AudioEngine) {
  22400. if (this._headphone) {
  22401. this._switchAudioModeForHeadphones();
  22402. }
  22403. else {
  22404. this._switchAudioModeForNormalSpeakers();
  22405. }
  22406. }
  22407. },
  22408. enumerable: true,
  22409. configurable: true
  22410. });
  22411. Scene.prototype._switchAudioModeForHeadphones = function () {
  22412. this.mainSoundTrack.switchPanningModelToHRTF();
  22413. for (var i = 0; i < this.soundTracks.length; i++) {
  22414. this.soundTracks[i].switchPanningModelToHRTF();
  22415. }
  22416. };
  22417. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22418. this.mainSoundTrack.switchPanningModelToEqualPower();
  22419. for (var i = 0; i < this.soundTracks.length; i++) {
  22420. this.soundTracks[i].switchPanningModelToEqualPower();
  22421. }
  22422. };
  22423. Scene.prototype.enableDepthRenderer = function () {
  22424. if (this._depthRenderer) {
  22425. return this._depthRenderer;
  22426. }
  22427. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22428. return this._depthRenderer;
  22429. };
  22430. Scene.prototype.disableDepthRenderer = function () {
  22431. if (!this._depthRenderer) {
  22432. return;
  22433. }
  22434. this._depthRenderer.dispose();
  22435. this._depthRenderer = null;
  22436. };
  22437. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  22438. if (ratio === void 0) { ratio = 1; }
  22439. if (this._geometryBufferRenderer) {
  22440. return this._geometryBufferRenderer;
  22441. }
  22442. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  22443. if (!this._geometryBufferRenderer.isSupported) {
  22444. this._geometryBufferRenderer = null;
  22445. }
  22446. return this._geometryBufferRenderer;
  22447. };
  22448. Scene.prototype.disableGeometryBufferRenderer = function () {
  22449. if (!this._geometryBufferRenderer) {
  22450. return;
  22451. }
  22452. this._geometryBufferRenderer.dispose();
  22453. this._geometryBufferRenderer = null;
  22454. };
  22455. Scene.prototype.freezeMaterials = function () {
  22456. for (var i = 0; i < this.materials.length; i++) {
  22457. this.materials[i].freeze();
  22458. }
  22459. };
  22460. Scene.prototype.unfreezeMaterials = function () {
  22461. for (var i = 0; i < this.materials.length; i++) {
  22462. this.materials[i].unfreeze();
  22463. }
  22464. };
  22465. Scene.prototype.dispose = function () {
  22466. this.beforeRender = null;
  22467. this.afterRender = null;
  22468. this.skeletons = [];
  22469. this.morphTargetManagers = [];
  22470. this.importedMeshesFiles = new Array();
  22471. this.stopAllAnimations();
  22472. this.resetCachedMaterial();
  22473. if (this._depthRenderer) {
  22474. this._depthRenderer.dispose();
  22475. }
  22476. if (this._gamepadManager) {
  22477. this._gamepadManager.dispose();
  22478. this._gamepadManager = null;
  22479. }
  22480. // Smart arrays
  22481. if (this.activeCamera) {
  22482. this.activeCamera._activeMeshes.dispose();
  22483. this.activeCamera = null;
  22484. }
  22485. this._activeMeshes.dispose();
  22486. this._renderingManager.dispose();
  22487. this._processedMaterials.dispose();
  22488. this._activeParticleSystems.dispose();
  22489. this._activeSkeletons.dispose();
  22490. this._softwareSkinnedMeshes.dispose();
  22491. this._renderTargets.dispose();
  22492. if (this._boundingBoxRenderer) {
  22493. this._boundingBoxRenderer.dispose();
  22494. }
  22495. this._meshesForIntersections.dispose();
  22496. this._toBeDisposed.dispose();
  22497. // Abort active requests
  22498. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  22499. var request = _a[_i];
  22500. request.abort();
  22501. }
  22502. // Debug layer
  22503. if (this._debugLayer) {
  22504. this._debugLayer.hide();
  22505. }
  22506. // Events
  22507. this.onDisposeObservable.notifyObservers(this);
  22508. this.onDisposeObservable.clear();
  22509. this.onBeforeRenderObservable.clear();
  22510. this.onAfterRenderObservable.clear();
  22511. this.OnBeforeRenderTargetsRenderObservable.clear();
  22512. this.OnAfterRenderTargetsRenderObservable.clear();
  22513. this.onAfterStepObservable.clear();
  22514. this.onBeforeStepObservable.clear();
  22515. this.onBeforeActiveMeshesEvaluationObservable.clear();
  22516. this.onAfterActiveMeshesEvaluationObservable.clear();
  22517. this.onBeforeParticlesRenderingObservable.clear();
  22518. this.onAfterParticlesRenderingObservable.clear();
  22519. this.onBeforeSpritesRenderingObservable.clear();
  22520. this.onAfterSpritesRenderingObservable.clear();
  22521. this.onBeforeDrawPhaseObservable.clear();
  22522. this.onAfterDrawPhaseObservable.clear();
  22523. this.onBeforePhysicsObservable.clear();
  22524. this.onAfterPhysicsObservable.clear();
  22525. this.onBeforeAnimationsObservable.clear();
  22526. this.onAfterAnimationsObservable.clear();
  22527. this.onDataLoadedObservable.clear();
  22528. this.detachControl();
  22529. // Release sounds & sounds tracks
  22530. if (BABYLON.AudioEngine) {
  22531. this.disposeSounds();
  22532. }
  22533. // VR Helper
  22534. if (this.VRHelper) {
  22535. this.VRHelper.dispose();
  22536. }
  22537. // Detach cameras
  22538. var canvas = this._engine.getRenderingCanvas();
  22539. if (canvas) {
  22540. var index;
  22541. for (index = 0; index < this.cameras.length; index++) {
  22542. this.cameras[index].detachControl(canvas);
  22543. }
  22544. }
  22545. // Release animation groups
  22546. while (this.animationGroups.length) {
  22547. this.animationGroups[0].dispose();
  22548. }
  22549. // Release lights
  22550. while (this.lights.length) {
  22551. this.lights[0].dispose();
  22552. }
  22553. // Release meshes
  22554. while (this.meshes.length) {
  22555. this.meshes[0].dispose(true);
  22556. }
  22557. while (this.transformNodes.length) {
  22558. this.removeTransformNode(this.transformNodes[0]);
  22559. }
  22560. // Release cameras
  22561. while (this.cameras.length) {
  22562. this.cameras[0].dispose();
  22563. }
  22564. // Release materials
  22565. if (this.defaultMaterial) {
  22566. this.defaultMaterial.dispose();
  22567. }
  22568. while (this.multiMaterials.length) {
  22569. this.multiMaterials[0].dispose();
  22570. }
  22571. while (this.materials.length) {
  22572. this.materials[0].dispose();
  22573. }
  22574. // Release particles
  22575. while (this.particleSystems.length) {
  22576. this.particleSystems[0].dispose();
  22577. }
  22578. // Release sprites
  22579. while (this.spriteManagers.length) {
  22580. this.spriteManagers[0].dispose();
  22581. }
  22582. // Release postProcesses
  22583. while (this.postProcesses.length) {
  22584. this.postProcesses[0].dispose();
  22585. }
  22586. // Release layers
  22587. while (this.layers.length) {
  22588. this.layers[0].dispose();
  22589. }
  22590. while (this.highlightLayers.length) {
  22591. this.highlightLayers[0].dispose();
  22592. }
  22593. // Release textures
  22594. while (this.textures.length) {
  22595. this.textures[0].dispose();
  22596. }
  22597. // Release UBO
  22598. this._sceneUbo.dispose();
  22599. if (this._alternateSceneUbo) {
  22600. this._alternateSceneUbo.dispose();
  22601. }
  22602. // Post-processes
  22603. this.postProcessManager.dispose();
  22604. if (this._postProcessRenderPipelineManager) {
  22605. this._postProcessRenderPipelineManager.dispose();
  22606. }
  22607. // Physics
  22608. if (this._physicsEngine) {
  22609. this.disablePhysicsEngine();
  22610. }
  22611. // Remove from engine
  22612. index = this._engine.scenes.indexOf(this);
  22613. if (index > -1) {
  22614. this._engine.scenes.splice(index, 1);
  22615. }
  22616. this._engine.wipeCaches(true);
  22617. this._isDisposed = true;
  22618. };
  22619. Object.defineProperty(Scene.prototype, "isDisposed", {
  22620. get: function () {
  22621. return this._isDisposed;
  22622. },
  22623. enumerable: true,
  22624. configurable: true
  22625. });
  22626. // Release sounds & sounds tracks
  22627. Scene.prototype.disposeSounds = function () {
  22628. if (!this._mainSoundTrack) {
  22629. return;
  22630. }
  22631. this.mainSoundTrack.dispose();
  22632. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22633. this.soundTracks[scIndex].dispose();
  22634. }
  22635. };
  22636. // Octrees
  22637. Scene.prototype.getWorldExtends = function () {
  22638. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22639. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22640. for (var index = 0; index < this.meshes.length; index++) {
  22641. var mesh = this.meshes[index];
  22642. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  22643. continue;
  22644. }
  22645. mesh.computeWorldMatrix(true);
  22646. var boundingInfo = mesh.getBoundingInfo();
  22647. var minBox = boundingInfo.boundingBox.minimumWorld;
  22648. var maxBox = boundingInfo.boundingBox.maximumWorld;
  22649. BABYLON.Tools.CheckExtends(minBox, min, max);
  22650. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22651. }
  22652. return {
  22653. min: min,
  22654. max: max
  22655. };
  22656. };
  22657. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22658. if (maxCapacity === void 0) { maxCapacity = 64; }
  22659. if (maxDepth === void 0) { maxDepth = 2; }
  22660. if (!this._selectionOctree) {
  22661. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  22662. }
  22663. var worldExtends = this.getWorldExtends();
  22664. // Update octree
  22665. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  22666. return this._selectionOctree;
  22667. };
  22668. // Picking
  22669. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  22670. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22671. var result = BABYLON.Ray.Zero();
  22672. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  22673. return result;
  22674. };
  22675. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  22676. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22677. var engine = this._engine;
  22678. if (!camera) {
  22679. if (!this.activeCamera)
  22680. throw new Error("Active camera not set");
  22681. camera = this.activeCamera;
  22682. }
  22683. var cameraViewport = camera.viewport;
  22684. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22685. // Moving coordinates to local viewport world
  22686. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22687. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22688. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  22689. return this;
  22690. };
  22691. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22692. var result = BABYLON.Ray.Zero();
  22693. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  22694. return result;
  22695. };
  22696. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  22697. if (!BABYLON.PickingInfo) {
  22698. return this;
  22699. }
  22700. var engine = this._engine;
  22701. if (!camera) {
  22702. if (!this.activeCamera)
  22703. throw new Error("Active camera not set");
  22704. camera = this.activeCamera;
  22705. }
  22706. var cameraViewport = camera.viewport;
  22707. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22708. var identity = BABYLON.Matrix.Identity();
  22709. // Moving coordinates to local viewport world
  22710. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22711. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22712. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22713. return this;
  22714. };
  22715. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22716. if (!BABYLON.PickingInfo) {
  22717. return null;
  22718. }
  22719. var pickingInfo = null;
  22720. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22721. var mesh = this.meshes[meshIndex];
  22722. if (predicate) {
  22723. if (!predicate(mesh)) {
  22724. continue;
  22725. }
  22726. }
  22727. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22728. continue;
  22729. }
  22730. var world = mesh.getWorldMatrix();
  22731. var ray = rayFunction(world);
  22732. var result = mesh.intersects(ray, fastCheck);
  22733. if (!result || !result.hit)
  22734. continue;
  22735. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22736. continue;
  22737. pickingInfo = result;
  22738. if (fastCheck) {
  22739. break;
  22740. }
  22741. }
  22742. return pickingInfo || new BABYLON.PickingInfo();
  22743. };
  22744. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22745. if (!BABYLON.PickingInfo) {
  22746. return null;
  22747. }
  22748. var pickingInfos = new Array();
  22749. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22750. var mesh = this.meshes[meshIndex];
  22751. if (predicate) {
  22752. if (!predicate(mesh)) {
  22753. continue;
  22754. }
  22755. }
  22756. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22757. continue;
  22758. }
  22759. var world = mesh.getWorldMatrix();
  22760. var ray = rayFunction(world);
  22761. var result = mesh.intersects(ray, false);
  22762. if (!result || !result.hit)
  22763. continue;
  22764. pickingInfos.push(result);
  22765. }
  22766. return pickingInfos;
  22767. };
  22768. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22769. if (!BABYLON.PickingInfo) {
  22770. return null;
  22771. }
  22772. var pickingInfo = null;
  22773. if (!camera) {
  22774. if (!this.activeCamera) {
  22775. return null;
  22776. }
  22777. camera = this.activeCamera;
  22778. }
  22779. if (this.spriteManagers.length > 0) {
  22780. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22781. var spriteManager = this.spriteManagers[spriteIndex];
  22782. if (!spriteManager.isPickable) {
  22783. continue;
  22784. }
  22785. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22786. if (!result || !result.hit)
  22787. continue;
  22788. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22789. continue;
  22790. pickingInfo = result;
  22791. if (fastCheck) {
  22792. break;
  22793. }
  22794. }
  22795. }
  22796. return pickingInfo || new BABYLON.PickingInfo();
  22797. };
  22798. /** Launch a ray to try to pick a mesh in the scene
  22799. * @param x position on screen
  22800. * @param y position on screen
  22801. * @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
  22802. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22803. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22804. */
  22805. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22806. var _this = this;
  22807. if (!BABYLON.PickingInfo) {
  22808. return null;
  22809. }
  22810. return this._internalPick(function (world) {
  22811. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  22812. return _this._tempPickingRay;
  22813. }, predicate, fastCheck);
  22814. };
  22815. /** Launch a ray to try to pick a sprite in the scene
  22816. * @param x position on screen
  22817. * @param y position on screen
  22818. * @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
  22819. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22820. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22821. */
  22822. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22823. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  22824. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  22825. };
  22826. /** Use the given ray to pick a mesh in the scene
  22827. * @param ray The ray to use to pick meshes
  22828. * @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
  22829. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22830. */
  22831. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22832. var _this = this;
  22833. return this._internalPick(function (world) {
  22834. if (!_this._pickWithRayInverseMatrix) {
  22835. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22836. }
  22837. world.invertToRef(_this._pickWithRayInverseMatrix);
  22838. if (!_this._cachedRayForTransform) {
  22839. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22840. }
  22841. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22842. return _this._cachedRayForTransform;
  22843. }, predicate, fastCheck);
  22844. };
  22845. /**
  22846. * Launch a ray to try to pick a mesh in the scene
  22847. * @param x X position on screen
  22848. * @param y Y position on screen
  22849. * @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
  22850. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22851. */
  22852. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22853. var _this = this;
  22854. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  22855. };
  22856. /**
  22857. * Launch a ray to try to pick a mesh in the scene
  22858. * @param ray Ray to use
  22859. * @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
  22860. */
  22861. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22862. var _this = this;
  22863. return this._internalMultiPick(function (world) {
  22864. if (!_this._pickWithRayInverseMatrix) {
  22865. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22866. }
  22867. world.invertToRef(_this._pickWithRayInverseMatrix);
  22868. if (!_this._cachedRayForTransform) {
  22869. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22870. }
  22871. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22872. return _this._cachedRayForTransform;
  22873. }, predicate);
  22874. };
  22875. Scene.prototype.setPointerOverMesh = function (mesh) {
  22876. if (this._pointerOverMesh === mesh) {
  22877. return;
  22878. }
  22879. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22880. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22881. }
  22882. this._pointerOverMesh = mesh;
  22883. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22884. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22885. }
  22886. };
  22887. Scene.prototype.getPointerOverMesh = function () {
  22888. return this._pointerOverMesh;
  22889. };
  22890. Scene.prototype.setPointerOverSprite = function (sprite) {
  22891. if (this._pointerOverSprite === sprite) {
  22892. return;
  22893. }
  22894. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22895. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22896. }
  22897. this._pointerOverSprite = sprite;
  22898. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22899. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22900. }
  22901. };
  22902. Scene.prototype.getPointerOverSprite = function () {
  22903. return this._pointerOverSprite;
  22904. };
  22905. // Physics
  22906. Scene.prototype.getPhysicsEngine = function () {
  22907. return this._physicsEngine;
  22908. };
  22909. /**
  22910. * Enables physics to the current scene
  22911. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22912. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22913. * @return {boolean} was the physics engine initialized
  22914. */
  22915. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22916. if (gravity === void 0) { gravity = null; }
  22917. if (this._physicsEngine) {
  22918. return true;
  22919. }
  22920. try {
  22921. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22922. return true;
  22923. }
  22924. catch (e) {
  22925. BABYLON.Tools.Error(e.message);
  22926. return false;
  22927. }
  22928. };
  22929. Scene.prototype.disablePhysicsEngine = function () {
  22930. if (!this._physicsEngine) {
  22931. return;
  22932. }
  22933. this._physicsEngine.dispose();
  22934. this._physicsEngine = null;
  22935. };
  22936. Scene.prototype.isPhysicsEnabled = function () {
  22937. return this._physicsEngine !== undefined;
  22938. };
  22939. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22940. var mesh = compound.parts[0].mesh;
  22941. if (mesh.physicsImpostor) {
  22942. mesh.physicsImpostor.dispose();
  22943. mesh.physicsImpostor = null;
  22944. }
  22945. };
  22946. // Misc.
  22947. Scene.prototype._rebuildGeometries = function () {
  22948. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  22949. var geometry = _a[_i];
  22950. geometry._rebuild();
  22951. }
  22952. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  22953. var mesh = _c[_b];
  22954. mesh._rebuild();
  22955. }
  22956. if (this.postProcessManager) {
  22957. this.postProcessManager._rebuild();
  22958. }
  22959. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  22960. var layer = _e[_d];
  22961. layer._rebuild();
  22962. }
  22963. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  22964. var highlightLayer = _g[_f];
  22965. highlightLayer._rebuild();
  22966. }
  22967. if (this._boundingBoxRenderer) {
  22968. this._boundingBoxRenderer._rebuild();
  22969. }
  22970. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  22971. var system = _j[_h];
  22972. system.rebuild();
  22973. }
  22974. if (this._postProcessRenderPipelineManager) {
  22975. this._postProcessRenderPipelineManager._rebuild();
  22976. }
  22977. };
  22978. Scene.prototype._rebuildTextures = function () {
  22979. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  22980. var texture = _a[_i];
  22981. texture._rebuild();
  22982. }
  22983. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22984. };
  22985. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  22986. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  22987. if (replace === void 0) { replace = false; }
  22988. if (attachCameraControls === void 0) { attachCameraControls = false; }
  22989. // Dispose existing camera or light in replace mode.
  22990. if (replace) {
  22991. if (this.activeCamera) {
  22992. this.activeCamera.dispose();
  22993. this.activeCamera = null;
  22994. }
  22995. if (this.lights) {
  22996. for (var i = 0; i < this.lights.length; i++) {
  22997. this.lights[i].dispose();
  22998. }
  22999. }
  23000. }
  23001. // Light
  23002. if (this.lights.length === 0) {
  23003. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23004. }
  23005. // Camera
  23006. if (!this.activeCamera) {
  23007. var worldExtends = this.getWorldExtends();
  23008. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23009. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23010. var camera;
  23011. var radius = worldSize.length() * 1.5;
  23012. if (createArcRotateCamera) {
  23013. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23014. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23015. arcRotateCamera.wheelPrecision = 100 / radius;
  23016. camera = arcRotateCamera;
  23017. }
  23018. else {
  23019. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23020. freeCamera.setTarget(worldCenter);
  23021. camera = freeCamera;
  23022. }
  23023. camera.minZ = radius * 0.01;
  23024. camera.maxZ = radius * 1000;
  23025. camera.speed = radius * 0.2;
  23026. this.activeCamera = camera;
  23027. var canvas = this.getEngine().getRenderingCanvas();
  23028. if (attachCameraControls && canvas) {
  23029. camera.attachControl(canvas);
  23030. }
  23031. }
  23032. };
  23033. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23034. if (pbr === void 0) { pbr = false; }
  23035. if (scale === void 0) { scale = 1000; }
  23036. if (blur === void 0) { blur = 0; }
  23037. if (environmentTexture) {
  23038. this.environmentTexture = environmentTexture;
  23039. }
  23040. if (!this.environmentTexture) {
  23041. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23042. return null;
  23043. }
  23044. // Skybox
  23045. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23046. if (pbr) {
  23047. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23048. hdrSkyboxMaterial.backFaceCulling = false;
  23049. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23050. if (hdrSkyboxMaterial.reflectionTexture) {
  23051. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23052. }
  23053. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23054. hdrSkyboxMaterial.disableLighting = true;
  23055. hdrSkyboxMaterial.twoSidedLighting = true;
  23056. hdrSkybox.infiniteDistance = true;
  23057. hdrSkybox.material = hdrSkyboxMaterial;
  23058. }
  23059. else {
  23060. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23061. skyboxMaterial.backFaceCulling = false;
  23062. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23063. if (skyboxMaterial.reflectionTexture) {
  23064. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23065. }
  23066. skyboxMaterial.disableLighting = true;
  23067. hdrSkybox.infiniteDistance = true;
  23068. hdrSkybox.material = skyboxMaterial;
  23069. }
  23070. return hdrSkybox;
  23071. };
  23072. Scene.prototype.createDefaultEnvironment = function (options) {
  23073. if (BABYLON.EnvironmentHelper) {
  23074. return new BABYLON.EnvironmentHelper(options, this);
  23075. }
  23076. return null;
  23077. };
  23078. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23079. if (webVROptions === void 0) { webVROptions = {}; }
  23080. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23081. };
  23082. // Tags
  23083. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23084. if (tagsQuery === undefined) {
  23085. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23086. return list;
  23087. }
  23088. var listByTags = [];
  23089. forEach = forEach || (function (item) { return; });
  23090. for (var i in list) {
  23091. var item = list[i];
  23092. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23093. listByTags.push(item);
  23094. forEach(item);
  23095. }
  23096. }
  23097. return listByTags;
  23098. };
  23099. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23100. return this._getByTags(this.meshes, tagsQuery, forEach);
  23101. };
  23102. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23103. return this._getByTags(this.cameras, tagsQuery, forEach);
  23104. };
  23105. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23106. return this._getByTags(this.lights, tagsQuery, forEach);
  23107. };
  23108. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23109. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23110. };
  23111. /**
  23112. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23113. * This allowed control for front to back rendering or reversly depending of the special needs.
  23114. *
  23115. * @param renderingGroupId The rendering group id corresponding to its index
  23116. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23117. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23118. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23119. */
  23120. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23121. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23122. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23123. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23124. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23125. };
  23126. /**
  23127. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23128. *
  23129. * @param renderingGroupId The rendering group id corresponding to its index
  23130. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23131. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23132. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23133. */
  23134. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23135. if (depth === void 0) { depth = true; }
  23136. if (stencil === void 0) { stencil = true; }
  23137. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23138. };
  23139. /**
  23140. * Will flag all materials as dirty to trigger new shader compilation
  23141. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23142. */
  23143. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23144. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23145. var material = _a[_i];
  23146. if (predicate && !predicate(material)) {
  23147. continue;
  23148. }
  23149. material.markAsDirty(flag);
  23150. }
  23151. };
  23152. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23153. var _this = this;
  23154. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23155. this._activeRequests.push(request);
  23156. request.onCompleteObservable.add(function (request) {
  23157. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23158. });
  23159. return request;
  23160. };
  23161. // Statics
  23162. Scene._FOGMODE_NONE = 0;
  23163. Scene._FOGMODE_EXP = 1;
  23164. Scene._FOGMODE_EXP2 = 2;
  23165. Scene._FOGMODE_LINEAR = 3;
  23166. Scene._uniqueIdCounter = 0;
  23167. Scene.MinDeltaTime = 1.0;
  23168. Scene.MaxDeltaTime = 1000.0;
  23169. /** The distance in pixel that you have to move to prevent some events */
  23170. Scene.DragMovementThreshold = 10; // in pixels
  23171. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23172. Scene.LongPressDelay = 500; // in milliseconds
  23173. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23174. Scene.DoubleClickDelay = 300; // in milliseconds
  23175. /** If you need to check double click without raising a single click at first click, enable this flag */
  23176. Scene.ExclusiveDoubleClickMode = false;
  23177. return Scene;
  23178. }());
  23179. BABYLON.Scene = Scene;
  23180. })(BABYLON || (BABYLON = {}));
  23181. //# sourceMappingURL=babylon.scene.js.map
  23182. var BABYLON;
  23183. (function (BABYLON) {
  23184. var AssetContainer = /** @class */ (function () {
  23185. function AssetContainer(scene) {
  23186. // Objects
  23187. this.cameras = new Array();
  23188. this.lights = new Array();
  23189. this.meshes = new Array();
  23190. this.skeletons = new Array();
  23191. this.particleSystems = new Array();
  23192. this.animations = new Array();
  23193. this.multiMaterials = new Array();
  23194. this.materials = new Array();
  23195. this.morphTargetManagers = new Array();
  23196. this.geometries = new Array();
  23197. this.transformNodes = new Array();
  23198. this.lensFlareSystems = new Array();
  23199. this.shadowGenerators = new Array();
  23200. this.actionManagers = new Array();
  23201. this.sounds = new Array();
  23202. this.scene = scene;
  23203. }
  23204. AssetContainer.prototype.addAllToScene = function () {
  23205. var _this = this;
  23206. this.cameras.forEach(function (o) {
  23207. _this.scene.addCamera(o);
  23208. });
  23209. this.lights.forEach(function (o) {
  23210. _this.scene.addLight(o);
  23211. });
  23212. this.meshes.forEach(function (o) {
  23213. _this.scene.addMesh(o);
  23214. });
  23215. this.skeletons.forEach(function (o) {
  23216. _this.scene.addSkeleton(o);
  23217. });
  23218. this.particleSystems.forEach(function (o) {
  23219. _this.scene.addParticleSystem(o);
  23220. });
  23221. this.animations.forEach(function (o) {
  23222. _this.scene.addAnimation(o);
  23223. });
  23224. this.multiMaterials.forEach(function (o) {
  23225. _this.scene.addMultiMaterial(o);
  23226. });
  23227. this.materials.forEach(function (o) {
  23228. _this.scene.addMaterial(o);
  23229. });
  23230. this.morphTargetManagers.forEach(function (o) {
  23231. _this.scene.addMorphTargetManager(o);
  23232. });
  23233. this.geometries.forEach(function (o) {
  23234. _this.scene.addGeometry(o);
  23235. });
  23236. this.transformNodes.forEach(function (o) {
  23237. _this.scene.addTransformNode(o);
  23238. });
  23239. this.lensFlareSystems.forEach(function (o) {
  23240. _this.scene.addLensFlareSystem(o);
  23241. });
  23242. this.actionManagers.forEach(function (o) {
  23243. _this.scene.addActionManager(o);
  23244. });
  23245. this.sounds.forEach(function (o) {
  23246. o.play();
  23247. o.autoplay = true;
  23248. _this.scene.mainSoundTrack.AddSound(o);
  23249. });
  23250. };
  23251. AssetContainer.prototype.removeAllFromScene = function () {
  23252. var _this = this;
  23253. this.cameras.forEach(function (o) {
  23254. _this.scene.removeCamera(o);
  23255. });
  23256. this.lights.forEach(function (o) {
  23257. _this.scene.removeLight(o);
  23258. });
  23259. this.meshes.forEach(function (o) {
  23260. _this.scene.removeMesh(o);
  23261. });
  23262. this.skeletons.forEach(function (o) {
  23263. _this.scene.removeSkeleton(o);
  23264. });
  23265. this.particleSystems.forEach(function (o) {
  23266. _this.scene.removeParticleSystem(o);
  23267. });
  23268. this.animations.forEach(function (o) {
  23269. _this.scene.removeAnimation(o);
  23270. });
  23271. this.multiMaterials.forEach(function (o) {
  23272. _this.scene.removeMultiMaterial(o);
  23273. });
  23274. this.materials.forEach(function (o) {
  23275. _this.scene.removeMaterial(o);
  23276. });
  23277. this.morphTargetManagers.forEach(function (o) {
  23278. _this.scene.removeMorphTargetManager(o);
  23279. });
  23280. this.geometries.forEach(function (o) {
  23281. _this.scene.removeGeometry(o);
  23282. });
  23283. this.transformNodes.forEach(function (o) {
  23284. _this.scene.removeTransformNode(o);
  23285. });
  23286. this.lensFlareSystems.forEach(function (o) {
  23287. _this.scene.removeLensFlareSystem(o);
  23288. });
  23289. this.actionManagers.forEach(function (o) {
  23290. _this.scene.removeActionManager(o);
  23291. });
  23292. this.sounds.forEach(function (o) {
  23293. o.stop();
  23294. o.autoplay = false;
  23295. _this.scene.mainSoundTrack.RemoveSound(o);
  23296. });
  23297. };
  23298. return AssetContainer;
  23299. }());
  23300. BABYLON.AssetContainer = AssetContainer;
  23301. })(BABYLON || (BABYLON = {}));
  23302. //# sourceMappingURL=babylon.assetContainer.js.map
  23303. var BABYLON;
  23304. (function (BABYLON) {
  23305. var Buffer = /** @class */ (function () {
  23306. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23307. if (instanced === void 0) { instanced = false; }
  23308. if (engine instanceof BABYLON.Mesh) {
  23309. this._engine = engine.getScene().getEngine();
  23310. }
  23311. else {
  23312. this._engine = engine;
  23313. }
  23314. this._updatable = updatable;
  23315. this._data = data;
  23316. this._strideSize = stride;
  23317. if (!postponeInternalCreation) {
  23318. this.create();
  23319. }
  23320. this._instanced = instanced;
  23321. this._instanceDivisor = instanced ? 1 : 0;
  23322. }
  23323. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23324. // a lot of these parameters are ignored as they are overriden by the buffer
  23325. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23326. };
  23327. // Properties
  23328. Buffer.prototype.isUpdatable = function () {
  23329. return this._updatable;
  23330. };
  23331. Buffer.prototype.getData = function () {
  23332. return this._data;
  23333. };
  23334. Buffer.prototype.getBuffer = function () {
  23335. return this._buffer;
  23336. };
  23337. Buffer.prototype.getStrideSize = function () {
  23338. return this._strideSize;
  23339. };
  23340. Buffer.prototype.getIsInstanced = function () {
  23341. return this._instanced;
  23342. };
  23343. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  23344. get: function () {
  23345. return this._instanceDivisor;
  23346. },
  23347. set: function (value) {
  23348. this._instanceDivisor = value;
  23349. if (value == 0) {
  23350. this._instanced = false;
  23351. }
  23352. else {
  23353. this._instanced = true;
  23354. }
  23355. },
  23356. enumerable: true,
  23357. configurable: true
  23358. });
  23359. // Methods
  23360. Buffer.prototype.create = function (data) {
  23361. if (data === void 0) { data = null; }
  23362. if (!data && this._buffer) {
  23363. return; // nothing to do
  23364. }
  23365. data = data || this._data;
  23366. if (!data) {
  23367. return;
  23368. }
  23369. if (!this._buffer) {
  23370. if (this._updatable) {
  23371. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23372. this._data = data;
  23373. }
  23374. else {
  23375. this._buffer = this._engine.createVertexBuffer(data);
  23376. }
  23377. }
  23378. else if (this._updatable) {
  23379. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23380. this._data = data;
  23381. }
  23382. };
  23383. Buffer.prototype._rebuild = function () {
  23384. this._buffer = null;
  23385. this.create(this._data);
  23386. };
  23387. Buffer.prototype.update = function (data) {
  23388. this.create(data);
  23389. };
  23390. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23391. if (!this._buffer) {
  23392. return;
  23393. }
  23394. if (this._updatable) {
  23395. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23396. this._data = null;
  23397. }
  23398. };
  23399. Buffer.prototype.dispose = function () {
  23400. if (!this._buffer) {
  23401. return;
  23402. }
  23403. if (this._engine._releaseBuffer(this._buffer)) {
  23404. this._buffer = null;
  23405. }
  23406. };
  23407. return Buffer;
  23408. }());
  23409. BABYLON.Buffer = Buffer;
  23410. })(BABYLON || (BABYLON = {}));
  23411. //# sourceMappingURL=babylon.buffer.js.map
  23412. var BABYLON;
  23413. (function (BABYLON) {
  23414. var VertexBuffer = /** @class */ (function () {
  23415. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23416. if (!stride) {
  23417. // Deduce stride from kind
  23418. switch (kind) {
  23419. case VertexBuffer.PositionKind:
  23420. stride = 3;
  23421. break;
  23422. case VertexBuffer.NormalKind:
  23423. stride = 3;
  23424. break;
  23425. case VertexBuffer.UVKind:
  23426. case VertexBuffer.UV2Kind:
  23427. case VertexBuffer.UV3Kind:
  23428. case VertexBuffer.UV4Kind:
  23429. case VertexBuffer.UV5Kind:
  23430. case VertexBuffer.UV6Kind:
  23431. stride = 2;
  23432. break;
  23433. case VertexBuffer.TangentKind:
  23434. case VertexBuffer.ColorKind:
  23435. stride = 4;
  23436. break;
  23437. case VertexBuffer.MatricesIndicesKind:
  23438. case VertexBuffer.MatricesIndicesExtraKind:
  23439. stride = 4;
  23440. break;
  23441. case VertexBuffer.MatricesWeightsKind:
  23442. case VertexBuffer.MatricesWeightsExtraKind:
  23443. default:
  23444. stride = 4;
  23445. break;
  23446. }
  23447. }
  23448. if (data instanceof BABYLON.Buffer) {
  23449. if (!stride) {
  23450. stride = data.getStrideSize();
  23451. }
  23452. this._buffer = data;
  23453. this._ownsBuffer = false;
  23454. }
  23455. else {
  23456. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  23457. this._ownsBuffer = true;
  23458. }
  23459. this._stride = stride;
  23460. this._offset = offset ? offset : 0;
  23461. this._size = size ? size : stride;
  23462. this._kind = kind;
  23463. }
  23464. VertexBuffer.prototype._rebuild = function () {
  23465. if (!this._buffer) {
  23466. return;
  23467. }
  23468. this._buffer._rebuild();
  23469. };
  23470. /**
  23471. * Returns the kind of the VertexBuffer (string).
  23472. */
  23473. VertexBuffer.prototype.getKind = function () {
  23474. return this._kind;
  23475. };
  23476. // Properties
  23477. /**
  23478. * Boolean : is the VertexBuffer updatable ?
  23479. */
  23480. VertexBuffer.prototype.isUpdatable = function () {
  23481. return this._buffer.isUpdatable();
  23482. };
  23483. /**
  23484. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  23485. */
  23486. VertexBuffer.prototype.getData = function () {
  23487. return this._buffer.getData();
  23488. };
  23489. /**
  23490. * Returns the WebGLBuffer associated to the VertexBuffer.
  23491. */
  23492. VertexBuffer.prototype.getBuffer = function () {
  23493. return this._buffer.getBuffer();
  23494. };
  23495. /**
  23496. * Returns the stride of the VertexBuffer (integer).
  23497. */
  23498. VertexBuffer.prototype.getStrideSize = function () {
  23499. return this._stride;
  23500. };
  23501. /**
  23502. * Returns the offset (integer).
  23503. */
  23504. VertexBuffer.prototype.getOffset = function () {
  23505. return this._offset;
  23506. };
  23507. /**
  23508. * Returns the VertexBuffer total size (integer).
  23509. */
  23510. VertexBuffer.prototype.getSize = function () {
  23511. return this._size;
  23512. };
  23513. /**
  23514. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  23515. */
  23516. VertexBuffer.prototype.getIsInstanced = function () {
  23517. return this._buffer.getIsInstanced();
  23518. };
  23519. /**
  23520. * Returns the instancing divisor, zero for non-instanced (integer).
  23521. */
  23522. VertexBuffer.prototype.getInstanceDivisor = function () {
  23523. return this._buffer.instanceDivisor;
  23524. };
  23525. // Methods
  23526. /**
  23527. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  23528. * Returns the created WebGLBuffer.
  23529. */
  23530. VertexBuffer.prototype.create = function (data) {
  23531. return this._buffer.create(data);
  23532. };
  23533. /**
  23534. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23535. * Returns the updated WebGLBuffer.
  23536. */
  23537. VertexBuffer.prototype.update = function (data) {
  23538. return this._buffer.update(data);
  23539. };
  23540. /**
  23541. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23542. * Returns the directly updated WebGLBuffer.
  23543. */
  23544. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  23545. return this._buffer.updateDirectly(data, offset);
  23546. };
  23547. /**
  23548. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  23549. */
  23550. VertexBuffer.prototype.dispose = function () {
  23551. if (this._ownsBuffer) {
  23552. this._buffer.dispose();
  23553. }
  23554. };
  23555. Object.defineProperty(VertexBuffer, "PositionKind", {
  23556. get: function () {
  23557. return VertexBuffer._PositionKind;
  23558. },
  23559. enumerable: true,
  23560. configurable: true
  23561. });
  23562. Object.defineProperty(VertexBuffer, "NormalKind", {
  23563. get: function () {
  23564. return VertexBuffer._NormalKind;
  23565. },
  23566. enumerable: true,
  23567. configurable: true
  23568. });
  23569. Object.defineProperty(VertexBuffer, "TangentKind", {
  23570. get: function () {
  23571. return VertexBuffer._TangentKind;
  23572. },
  23573. enumerable: true,
  23574. configurable: true
  23575. });
  23576. Object.defineProperty(VertexBuffer, "UVKind", {
  23577. get: function () {
  23578. return VertexBuffer._UVKind;
  23579. },
  23580. enumerable: true,
  23581. configurable: true
  23582. });
  23583. Object.defineProperty(VertexBuffer, "UV2Kind", {
  23584. get: function () {
  23585. return VertexBuffer._UV2Kind;
  23586. },
  23587. enumerable: true,
  23588. configurable: true
  23589. });
  23590. Object.defineProperty(VertexBuffer, "UV3Kind", {
  23591. get: function () {
  23592. return VertexBuffer._UV3Kind;
  23593. },
  23594. enumerable: true,
  23595. configurable: true
  23596. });
  23597. Object.defineProperty(VertexBuffer, "UV4Kind", {
  23598. get: function () {
  23599. return VertexBuffer._UV4Kind;
  23600. },
  23601. enumerable: true,
  23602. configurable: true
  23603. });
  23604. Object.defineProperty(VertexBuffer, "UV5Kind", {
  23605. get: function () {
  23606. return VertexBuffer._UV5Kind;
  23607. },
  23608. enumerable: true,
  23609. configurable: true
  23610. });
  23611. Object.defineProperty(VertexBuffer, "UV6Kind", {
  23612. get: function () {
  23613. return VertexBuffer._UV6Kind;
  23614. },
  23615. enumerable: true,
  23616. configurable: true
  23617. });
  23618. Object.defineProperty(VertexBuffer, "ColorKind", {
  23619. get: function () {
  23620. return VertexBuffer._ColorKind;
  23621. },
  23622. enumerable: true,
  23623. configurable: true
  23624. });
  23625. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  23626. get: function () {
  23627. return VertexBuffer._MatricesIndicesKind;
  23628. },
  23629. enumerable: true,
  23630. configurable: true
  23631. });
  23632. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  23633. get: function () {
  23634. return VertexBuffer._MatricesWeightsKind;
  23635. },
  23636. enumerable: true,
  23637. configurable: true
  23638. });
  23639. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  23640. get: function () {
  23641. return VertexBuffer._MatricesIndicesExtraKind;
  23642. },
  23643. enumerable: true,
  23644. configurable: true
  23645. });
  23646. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  23647. get: function () {
  23648. return VertexBuffer._MatricesWeightsExtraKind;
  23649. },
  23650. enumerable: true,
  23651. configurable: true
  23652. });
  23653. // Enums
  23654. VertexBuffer._PositionKind = "position";
  23655. VertexBuffer._NormalKind = "normal";
  23656. VertexBuffer._TangentKind = "tangent";
  23657. VertexBuffer._UVKind = "uv";
  23658. VertexBuffer._UV2Kind = "uv2";
  23659. VertexBuffer._UV3Kind = "uv3";
  23660. VertexBuffer._UV4Kind = "uv4";
  23661. VertexBuffer._UV5Kind = "uv5";
  23662. VertexBuffer._UV6Kind = "uv6";
  23663. VertexBuffer._ColorKind = "color";
  23664. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  23665. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  23666. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  23667. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  23668. return VertexBuffer;
  23669. }());
  23670. BABYLON.VertexBuffer = VertexBuffer;
  23671. })(BABYLON || (BABYLON = {}));
  23672. //# sourceMappingURL=babylon.vertexBuffer.js.map
  23673. var BABYLON;
  23674. (function (BABYLON) {
  23675. var InternalTexture = /** @class */ (function () {
  23676. function InternalTexture(engine, dataSource) {
  23677. this.onLoadedObservable = new BABYLON.Observable();
  23678. // Private
  23679. this._initialSlot = -1;
  23680. this._designatedSlot = -1;
  23681. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  23682. this._references = 1;
  23683. this._engine = engine;
  23684. this._dataSource = dataSource;
  23685. this._webGLTexture = engine._createTexture();
  23686. }
  23687. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  23688. get: function () {
  23689. return this._dataSource;
  23690. },
  23691. enumerable: true,
  23692. configurable: true
  23693. });
  23694. InternalTexture.prototype.incrementReferences = function () {
  23695. this._references++;
  23696. };
  23697. InternalTexture.prototype.updateSize = function (width, height, depth) {
  23698. if (depth === void 0) { depth = 1; }
  23699. this.width = width;
  23700. this.height = height;
  23701. this.depth = depth;
  23702. this.baseWidth = width;
  23703. this.baseHeight = height;
  23704. this.baseDepth = depth;
  23705. this._size = width * height * depth;
  23706. };
  23707. InternalTexture.prototype._rebuild = function () {
  23708. var _this = this;
  23709. var proxy;
  23710. this.isReady = false;
  23711. this._cachedCoordinatesMode = null;
  23712. this._cachedWrapU = null;
  23713. this._cachedWrapV = null;
  23714. this._cachedAnisotropicFilteringLevel = null;
  23715. switch (this._dataSource) {
  23716. case InternalTexture.DATASOURCE_TEMP:
  23717. return;
  23718. case InternalTexture.DATASOURCE_URL:
  23719. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  23720. _this.isReady = true;
  23721. }, null, this._buffer, undefined, this.format);
  23722. proxy._swapAndDie(this);
  23723. return;
  23724. case InternalTexture.DATASOURCE_RAW:
  23725. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23726. proxy._swapAndDie(this);
  23727. this.isReady = true;
  23728. return;
  23729. case InternalTexture.DATASOURCE_RAW3D:
  23730. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23731. proxy._swapAndDie(this);
  23732. this.isReady = true;
  23733. return;
  23734. case InternalTexture.DATASOURCE_DYNAMIC:
  23735. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  23736. proxy._swapAndDie(this);
  23737. // The engine will make sure to update content so no need to flag it as isReady = true
  23738. return;
  23739. case InternalTexture.DATASOURCE_RENDERTARGET:
  23740. var options = new BABYLON.RenderTargetCreationOptions();
  23741. options.generateDepthBuffer = this._generateDepthBuffer;
  23742. options.generateMipMaps = this.generateMipMaps;
  23743. options.generateStencilBuffer = this._generateStencilBuffer;
  23744. options.samplingMode = this.samplingMode;
  23745. options.type = this.type;
  23746. if (this.isCube) {
  23747. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  23748. }
  23749. else {
  23750. var size = {
  23751. width: this.width,
  23752. height: this.height
  23753. };
  23754. proxy = this._engine.createRenderTargetTexture(size, options);
  23755. }
  23756. proxy._swapAndDie(this);
  23757. this.isReady = true;
  23758. return;
  23759. case InternalTexture.DATASOURCE_CUBE:
  23760. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  23761. _this.isReady = true;
  23762. }, null, this.format, this._extension);
  23763. proxy._swapAndDie(this);
  23764. return;
  23765. case InternalTexture.DATASOURCE_CUBERAW:
  23766. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23767. proxy._swapAndDie(this);
  23768. this.isReady = true;
  23769. return;
  23770. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  23771. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  23772. if (proxy) {
  23773. proxy._swapAndDie(_this);
  23774. }
  23775. _this.isReady = true;
  23776. }, null, this.format, this._extension);
  23777. return;
  23778. }
  23779. };
  23780. InternalTexture.prototype._swapAndDie = function (target) {
  23781. target._webGLTexture = this._webGLTexture;
  23782. if (this._framebuffer) {
  23783. target._framebuffer = this._framebuffer;
  23784. }
  23785. if (this._depthStencilBuffer) {
  23786. target._depthStencilBuffer = this._depthStencilBuffer;
  23787. }
  23788. if (this._lodTextureHigh) {
  23789. if (target._lodTextureHigh) {
  23790. target._lodTextureHigh.dispose();
  23791. }
  23792. target._lodTextureHigh = this._lodTextureHigh;
  23793. }
  23794. if (this._lodTextureMid) {
  23795. if (target._lodTextureMid) {
  23796. target._lodTextureMid.dispose();
  23797. }
  23798. target._lodTextureMid = this._lodTextureMid;
  23799. }
  23800. if (this._lodTextureLow) {
  23801. if (target._lodTextureLow) {
  23802. target._lodTextureLow.dispose();
  23803. }
  23804. target._lodTextureLow = this._lodTextureLow;
  23805. }
  23806. var cache = this._engine.getLoadedTexturesCache();
  23807. var index = cache.indexOf(this);
  23808. if (index !== -1) {
  23809. cache.splice(index, 1);
  23810. }
  23811. };
  23812. InternalTexture.prototype.dispose = function () {
  23813. if (!this._webGLTexture) {
  23814. return;
  23815. }
  23816. this._references--;
  23817. if (this._references === 0) {
  23818. this._engine._releaseTexture(this);
  23819. this._webGLTexture = null;
  23820. }
  23821. };
  23822. InternalTexture.DATASOURCE_UNKNOWN = 0;
  23823. InternalTexture.DATASOURCE_URL = 1;
  23824. InternalTexture.DATASOURCE_TEMP = 2;
  23825. InternalTexture.DATASOURCE_RAW = 3;
  23826. InternalTexture.DATASOURCE_DYNAMIC = 4;
  23827. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  23828. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  23829. InternalTexture.DATASOURCE_CUBE = 7;
  23830. InternalTexture.DATASOURCE_CUBERAW = 8;
  23831. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  23832. InternalTexture.DATASOURCE_RAW3D = 10;
  23833. return InternalTexture;
  23834. }());
  23835. BABYLON.InternalTexture = InternalTexture;
  23836. })(BABYLON || (BABYLON = {}));
  23837. //# sourceMappingURL=babylon.internalTexture.js.map
  23838. var BABYLON;
  23839. (function (BABYLON) {
  23840. var BaseTexture = /** @class */ (function () {
  23841. function BaseTexture(scene) {
  23842. this._hasAlpha = false;
  23843. this.getAlphaFromRGB = false;
  23844. this.level = 1;
  23845. this.coordinatesIndex = 0;
  23846. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23847. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23848. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23849. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  23850. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  23851. this.isCube = false;
  23852. this.is3D = false;
  23853. this.gammaSpace = true;
  23854. this.invertZ = false;
  23855. this.lodLevelInAlpha = false;
  23856. this.lodGenerationOffset = 0.0;
  23857. this.lodGenerationScale = 0.8;
  23858. this.isRenderTarget = false;
  23859. this.animations = new Array();
  23860. /**
  23861. * An event triggered when the texture is disposed.
  23862. * @type {BABYLON.Observable}
  23863. */
  23864. this.onDisposeObservable = new BABYLON.Observable();
  23865. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23866. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23867. if (this._scene) {
  23868. this._scene.textures.push(this);
  23869. }
  23870. this._uid = null;
  23871. }
  23872. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  23873. get: function () {
  23874. return this._hasAlpha;
  23875. },
  23876. set: function (value) {
  23877. if (this._hasAlpha === value) {
  23878. return;
  23879. }
  23880. this._hasAlpha = value;
  23881. if (this._scene) {
  23882. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23883. }
  23884. },
  23885. enumerable: true,
  23886. configurable: true
  23887. });
  23888. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  23889. get: function () {
  23890. return this._coordinatesMode;
  23891. },
  23892. set: function (value) {
  23893. if (this._coordinatesMode === value) {
  23894. return;
  23895. }
  23896. this._coordinatesMode = 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, "uid", {
  23905. get: function () {
  23906. if (!this._uid) {
  23907. this._uid = BABYLON.Tools.RandomId();
  23908. }
  23909. return this._uid;
  23910. },
  23911. enumerable: true,
  23912. configurable: true
  23913. });
  23914. BaseTexture.prototype.toString = function () {
  23915. return this.name;
  23916. };
  23917. BaseTexture.prototype.getClassName = function () {
  23918. return "BaseTexture";
  23919. };
  23920. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23921. set: function (callback) {
  23922. if (this._onDisposeObserver) {
  23923. this.onDisposeObservable.remove(this._onDisposeObserver);
  23924. }
  23925. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23926. },
  23927. enumerable: true,
  23928. configurable: true
  23929. });
  23930. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  23931. get: function () {
  23932. return true;
  23933. },
  23934. enumerable: true,
  23935. configurable: true
  23936. });
  23937. BaseTexture.prototype.getScene = function () {
  23938. return this._scene;
  23939. };
  23940. BaseTexture.prototype.getTextureMatrix = function () {
  23941. return BABYLON.Matrix.IdentityReadOnly;
  23942. };
  23943. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23944. return BABYLON.Matrix.IdentityReadOnly;
  23945. };
  23946. BaseTexture.prototype.getInternalTexture = function () {
  23947. return this._texture;
  23948. };
  23949. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  23950. return !this.isBlocking || this.isReady();
  23951. };
  23952. BaseTexture.prototype.isReady = function () {
  23953. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23954. this.delayLoad();
  23955. return false;
  23956. }
  23957. if (this._texture) {
  23958. return this._texture.isReady;
  23959. }
  23960. return false;
  23961. };
  23962. BaseTexture.prototype.getSize = function () {
  23963. if (this._texture && this._texture.width) {
  23964. return new BABYLON.Size(this._texture.width, this._texture.height);
  23965. }
  23966. if (this._texture && this._texture._size) {
  23967. return new BABYLON.Size(this._texture._size, this._texture._size);
  23968. }
  23969. return BABYLON.Size.Zero();
  23970. };
  23971. BaseTexture.prototype.getBaseSize = function () {
  23972. if (!this.isReady() || !this._texture)
  23973. return BABYLON.Size.Zero();
  23974. if (this._texture._size) {
  23975. return new BABYLON.Size(this._texture._size, this._texture._size);
  23976. }
  23977. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  23978. };
  23979. BaseTexture.prototype.scale = function (ratio) {
  23980. };
  23981. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  23982. get: function () {
  23983. return false;
  23984. },
  23985. enumerable: true,
  23986. configurable: true
  23987. });
  23988. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  23989. if (!this._scene) {
  23990. return null;
  23991. }
  23992. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23993. for (var index = 0; index < texturesCache.length; index++) {
  23994. var texturesCacheEntry = texturesCache[index];
  23995. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  23996. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  23997. texturesCacheEntry.incrementReferences();
  23998. return texturesCacheEntry;
  23999. }
  24000. }
  24001. }
  24002. return null;
  24003. };
  24004. BaseTexture.prototype._rebuild = function () {
  24005. };
  24006. BaseTexture.prototype.delayLoad = function () {
  24007. };
  24008. BaseTexture.prototype.clone = function () {
  24009. return null;
  24010. };
  24011. Object.defineProperty(BaseTexture.prototype, "textureType", {
  24012. get: function () {
  24013. if (!this._texture) {
  24014. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24015. }
  24016. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24017. },
  24018. enumerable: true,
  24019. configurable: true
  24020. });
  24021. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  24022. get: function () {
  24023. if (!this._texture) {
  24024. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24025. }
  24026. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24027. },
  24028. enumerable: true,
  24029. configurable: true
  24030. });
  24031. BaseTexture.prototype.readPixels = function (faceIndex) {
  24032. if (faceIndex === void 0) { faceIndex = 0; }
  24033. if (!this._texture) {
  24034. return null;
  24035. }
  24036. var size = this.getSize();
  24037. var scene = this.getScene();
  24038. if (!scene) {
  24039. return null;
  24040. }
  24041. var engine = scene.getEngine();
  24042. if (this._texture.isCube) {
  24043. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  24044. }
  24045. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  24046. };
  24047. BaseTexture.prototype.releaseInternalTexture = function () {
  24048. if (this._texture) {
  24049. this._texture.dispose();
  24050. this._texture = null;
  24051. }
  24052. };
  24053. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  24054. get: function () {
  24055. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  24056. return null;
  24057. }
  24058. if (!this._texture._sphericalPolynomial) {
  24059. this._texture._sphericalPolynomial =
  24060. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  24061. }
  24062. return this._texture._sphericalPolynomial;
  24063. },
  24064. set: function (value) {
  24065. if (this._texture) {
  24066. this._texture._sphericalPolynomial = value;
  24067. }
  24068. },
  24069. enumerable: true,
  24070. configurable: true
  24071. });
  24072. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  24073. get: function () {
  24074. if (this._texture) {
  24075. return this._texture._lodTextureHigh;
  24076. }
  24077. return null;
  24078. },
  24079. enumerable: true,
  24080. configurable: true
  24081. });
  24082. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  24083. get: function () {
  24084. if (this._texture) {
  24085. return this._texture._lodTextureMid;
  24086. }
  24087. return null;
  24088. },
  24089. enumerable: true,
  24090. configurable: true
  24091. });
  24092. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  24093. get: function () {
  24094. if (this._texture) {
  24095. return this._texture._lodTextureLow;
  24096. }
  24097. return null;
  24098. },
  24099. enumerable: true,
  24100. configurable: true
  24101. });
  24102. BaseTexture.prototype.dispose = function () {
  24103. if (!this._scene) {
  24104. return;
  24105. }
  24106. // Animations
  24107. this._scene.stopAnimation(this);
  24108. // Remove from scene
  24109. this._scene._removePendingData(this);
  24110. var index = this._scene.textures.indexOf(this);
  24111. if (index >= 0) {
  24112. this._scene.textures.splice(index, 1);
  24113. }
  24114. if (this._texture === undefined) {
  24115. return;
  24116. }
  24117. // Release
  24118. this.releaseInternalTexture();
  24119. // Callback
  24120. this.onDisposeObservable.notifyObservers(this);
  24121. this.onDisposeObservable.clear();
  24122. };
  24123. BaseTexture.prototype.serialize = function () {
  24124. if (!this.name) {
  24125. return null;
  24126. }
  24127. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24128. // Animations
  24129. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24130. return serializationObject;
  24131. };
  24132. BaseTexture.WhenAllReady = function (textures, callback) {
  24133. var numRemaining = textures.length;
  24134. if (numRemaining === 0) {
  24135. callback();
  24136. return;
  24137. }
  24138. var _loop_1 = function () {
  24139. texture = textures[i];
  24140. if (texture.isReady()) {
  24141. if (--numRemaining === 0) {
  24142. callback();
  24143. }
  24144. }
  24145. else {
  24146. onLoadObservable = texture.onLoadObservable;
  24147. var onLoadCallback_1 = function () {
  24148. onLoadObservable.removeCallback(onLoadCallback_1);
  24149. if (--numRemaining === 0) {
  24150. callback();
  24151. }
  24152. };
  24153. onLoadObservable.add(onLoadCallback_1);
  24154. }
  24155. };
  24156. var texture, onLoadObservable;
  24157. for (var i = 0; i < textures.length; i++) {
  24158. _loop_1();
  24159. }
  24160. };
  24161. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  24162. __decorate([
  24163. BABYLON.serialize()
  24164. ], BaseTexture.prototype, "name", void 0);
  24165. __decorate([
  24166. BABYLON.serialize("hasAlpha")
  24167. ], BaseTexture.prototype, "_hasAlpha", void 0);
  24168. __decorate([
  24169. BABYLON.serialize()
  24170. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  24171. __decorate([
  24172. BABYLON.serialize()
  24173. ], BaseTexture.prototype, "level", void 0);
  24174. __decorate([
  24175. BABYLON.serialize()
  24176. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  24177. __decorate([
  24178. BABYLON.serialize("coordinatesMode")
  24179. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  24180. __decorate([
  24181. BABYLON.serialize()
  24182. ], BaseTexture.prototype, "wrapU", void 0);
  24183. __decorate([
  24184. BABYLON.serialize()
  24185. ], BaseTexture.prototype, "wrapV", void 0);
  24186. __decorate([
  24187. BABYLON.serialize()
  24188. ], BaseTexture.prototype, "wrapR", void 0);
  24189. __decorate([
  24190. BABYLON.serialize()
  24191. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  24192. __decorate([
  24193. BABYLON.serialize()
  24194. ], BaseTexture.prototype, "isCube", void 0);
  24195. __decorate([
  24196. BABYLON.serialize()
  24197. ], BaseTexture.prototype, "is3D", void 0);
  24198. __decorate([
  24199. BABYLON.serialize()
  24200. ], BaseTexture.prototype, "gammaSpace", void 0);
  24201. __decorate([
  24202. BABYLON.serialize()
  24203. ], BaseTexture.prototype, "invertZ", void 0);
  24204. __decorate([
  24205. BABYLON.serialize()
  24206. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  24207. __decorate([
  24208. BABYLON.serialize()
  24209. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  24210. __decorate([
  24211. BABYLON.serialize()
  24212. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  24213. __decorate([
  24214. BABYLON.serialize()
  24215. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24216. return BaseTexture;
  24217. }());
  24218. BABYLON.BaseTexture = BaseTexture;
  24219. })(BABYLON || (BABYLON = {}));
  24220. //# sourceMappingURL=babylon.baseTexture.js.map
  24221. var BABYLON;
  24222. (function (BABYLON) {
  24223. var Texture = /** @class */ (function (_super) {
  24224. __extends(Texture, _super);
  24225. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  24226. if (noMipmap === void 0) { noMipmap = false; }
  24227. if (invertY === void 0) { invertY = true; }
  24228. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24229. if (onLoad === void 0) { onLoad = null; }
  24230. if (onError === void 0) { onError = null; }
  24231. if (buffer === void 0) { buffer = null; }
  24232. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24233. var _this = _super.call(this, scene) || this;
  24234. _this.uOffset = 0;
  24235. _this.vOffset = 0;
  24236. _this.uScale = 1.0;
  24237. _this.vScale = 1.0;
  24238. _this.uAng = 0;
  24239. _this.vAng = 0;
  24240. _this.wAng = 0;
  24241. _this._isBlocking = true;
  24242. _this.name = url || "";
  24243. _this.url = url;
  24244. _this._noMipmap = noMipmap;
  24245. _this._invertY = invertY;
  24246. _this._samplingMode = samplingMode;
  24247. _this._buffer = buffer;
  24248. _this._deleteBuffer = deleteBuffer;
  24249. if (format) {
  24250. _this._format = format;
  24251. }
  24252. scene = _this.getScene();
  24253. if (!scene) {
  24254. return _this;
  24255. }
  24256. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  24257. var load = function () {
  24258. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  24259. _this.onLoadObservable.notifyObservers(_this);
  24260. }
  24261. if (onLoad) {
  24262. onLoad();
  24263. }
  24264. if (!_this.isBlocking && scene) {
  24265. scene.resetCachedMaterial();
  24266. }
  24267. };
  24268. if (!_this.url) {
  24269. _this._delayedOnLoad = load;
  24270. _this._delayedOnError = onError;
  24271. return _this;
  24272. }
  24273. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  24274. if (!_this._texture) {
  24275. if (!scene.useDelayedTextureLoading) {
  24276. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  24277. if (deleteBuffer) {
  24278. delete _this._buffer;
  24279. }
  24280. }
  24281. else {
  24282. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24283. _this._delayedOnLoad = load;
  24284. _this._delayedOnError = onError;
  24285. }
  24286. }
  24287. else {
  24288. if (_this._texture.isReady) {
  24289. BABYLON.Tools.SetImmediate(function () { return load(); });
  24290. }
  24291. else {
  24292. _this._texture.onLoadedObservable.add(load);
  24293. }
  24294. }
  24295. return _this;
  24296. }
  24297. Object.defineProperty(Texture.prototype, "noMipmap", {
  24298. get: function () {
  24299. return this._noMipmap;
  24300. },
  24301. enumerable: true,
  24302. configurable: true
  24303. });
  24304. Object.defineProperty(Texture.prototype, "isBlocking", {
  24305. get: function () {
  24306. return this._isBlocking;
  24307. },
  24308. set: function (value) {
  24309. this._isBlocking = value;
  24310. },
  24311. enumerable: true,
  24312. configurable: true
  24313. });
  24314. Object.defineProperty(Texture.prototype, "samplingMode", {
  24315. get: function () {
  24316. return this._samplingMode;
  24317. },
  24318. enumerable: true,
  24319. configurable: true
  24320. });
  24321. Texture.prototype.updateURL = function (url) {
  24322. this.url = url;
  24323. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24324. this.delayLoad();
  24325. };
  24326. Texture.prototype.delayLoad = function () {
  24327. var _this = this;
  24328. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24329. return;
  24330. }
  24331. var scene = this.getScene();
  24332. if (!scene) {
  24333. return;
  24334. }
  24335. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24336. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24337. if (!this._texture) {
  24338. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  24339. if (this._deleteBuffer) {
  24340. delete this._buffer;
  24341. }
  24342. }
  24343. else {
  24344. if (this._texture.isReady) {
  24345. BABYLON.Tools.SetImmediate(function () {
  24346. if (!_this._delayedOnLoad) {
  24347. return;
  24348. }
  24349. _this._delayedOnLoad();
  24350. });
  24351. }
  24352. else {
  24353. if (this._delayedOnLoad) {
  24354. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  24355. }
  24356. }
  24357. }
  24358. };
  24359. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24360. if (!this._texture) {
  24361. return;
  24362. }
  24363. var scene = this.getScene();
  24364. if (!scene) {
  24365. return;
  24366. }
  24367. this._samplingMode = samplingMode;
  24368. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24369. };
  24370. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24371. x *= this.uScale;
  24372. y *= this.vScale;
  24373. x -= 0.5 * this.uScale;
  24374. y -= 0.5 * this.vScale;
  24375. z -= 0.5;
  24376. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24377. t.x += 0.5 * this.uScale + this.uOffset;
  24378. t.y += 0.5 * this.vScale + this.vOffset;
  24379. t.z += 0.5;
  24380. };
  24381. Texture.prototype.getTextureMatrix = function () {
  24382. var _this = this;
  24383. if (this.uOffset === this._cachedUOffset &&
  24384. this.vOffset === this._cachedVOffset &&
  24385. this.uScale === this._cachedUScale &&
  24386. this.vScale === this._cachedVScale &&
  24387. this.uAng === this._cachedUAng &&
  24388. this.vAng === this._cachedVAng &&
  24389. this.wAng === this._cachedWAng) {
  24390. return this._cachedTextureMatrix;
  24391. }
  24392. this._cachedUOffset = this.uOffset;
  24393. this._cachedVOffset = this.vOffset;
  24394. this._cachedUScale = this.uScale;
  24395. this._cachedVScale = this.vScale;
  24396. this._cachedUAng = this.uAng;
  24397. this._cachedVAng = this.vAng;
  24398. this._cachedWAng = this.wAng;
  24399. if (!this._cachedTextureMatrix) {
  24400. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24401. this._rowGenerationMatrix = new BABYLON.Matrix();
  24402. this._t0 = BABYLON.Vector3.Zero();
  24403. this._t1 = BABYLON.Vector3.Zero();
  24404. this._t2 = BABYLON.Vector3.Zero();
  24405. }
  24406. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24407. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24408. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24409. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24410. this._t1.subtractInPlace(this._t0);
  24411. this._t2.subtractInPlace(this._t0);
  24412. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24413. this._cachedTextureMatrix.m[0] = this._t1.x;
  24414. this._cachedTextureMatrix.m[1] = this._t1.y;
  24415. this._cachedTextureMatrix.m[2] = this._t1.z;
  24416. this._cachedTextureMatrix.m[4] = this._t2.x;
  24417. this._cachedTextureMatrix.m[5] = this._t2.y;
  24418. this._cachedTextureMatrix.m[6] = this._t2.z;
  24419. this._cachedTextureMatrix.m[8] = this._t0.x;
  24420. this._cachedTextureMatrix.m[9] = this._t0.y;
  24421. this._cachedTextureMatrix.m[10] = this._t0.z;
  24422. var scene = this.getScene();
  24423. if (!scene) {
  24424. return this._cachedTextureMatrix;
  24425. }
  24426. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24427. return mat.hasTexture(_this);
  24428. });
  24429. return this._cachedTextureMatrix;
  24430. };
  24431. Texture.prototype.getReflectionTextureMatrix = function () {
  24432. var _this = this;
  24433. var scene = this.getScene();
  24434. if (!scene) {
  24435. return this._cachedTextureMatrix;
  24436. }
  24437. if (this.uOffset === this._cachedUOffset &&
  24438. this.vOffset === this._cachedVOffset &&
  24439. this.uScale === this._cachedUScale &&
  24440. this.vScale === this._cachedVScale &&
  24441. this.coordinatesMode === this._cachedCoordinatesMode) {
  24442. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  24443. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  24444. return this._cachedTextureMatrix;
  24445. }
  24446. }
  24447. else {
  24448. return this._cachedTextureMatrix;
  24449. }
  24450. }
  24451. if (!this._cachedTextureMatrix) {
  24452. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24453. }
  24454. if (!this._projectionModeMatrix) {
  24455. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24456. }
  24457. this._cachedUOffset = this.uOffset;
  24458. this._cachedVOffset = this.vOffset;
  24459. this._cachedUScale = this.uScale;
  24460. this._cachedVScale = this.vScale;
  24461. this._cachedCoordinatesMode = this.coordinatesMode;
  24462. switch (this.coordinatesMode) {
  24463. case Texture.PLANAR_MODE:
  24464. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24465. this._cachedTextureMatrix[0] = this.uScale;
  24466. this._cachedTextureMatrix[5] = this.vScale;
  24467. this._cachedTextureMatrix[12] = this.uOffset;
  24468. this._cachedTextureMatrix[13] = this.vOffset;
  24469. break;
  24470. case Texture.PROJECTION_MODE:
  24471. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24472. this._projectionModeMatrix.m[0] = 0.5;
  24473. this._projectionModeMatrix.m[5] = -0.5;
  24474. this._projectionModeMatrix.m[10] = 0.0;
  24475. this._projectionModeMatrix.m[12] = 0.5;
  24476. this._projectionModeMatrix.m[13] = 0.5;
  24477. this._projectionModeMatrix.m[14] = 1.0;
  24478. this._projectionModeMatrix.m[15] = 1.0;
  24479. var projectionMatrix = scene.getProjectionMatrix();
  24480. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  24481. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24482. break;
  24483. default:
  24484. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24485. break;
  24486. }
  24487. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24488. return (mat.getActiveTextures().indexOf(_this) !== -1);
  24489. });
  24490. return this._cachedTextureMatrix;
  24491. };
  24492. Texture.prototype.clone = function () {
  24493. var _this = this;
  24494. return BABYLON.SerializationHelper.Clone(function () {
  24495. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24496. }, this);
  24497. };
  24498. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24499. get: function () {
  24500. if (!this._onLoadObservable) {
  24501. this._onLoadObservable = new BABYLON.Observable();
  24502. }
  24503. return this._onLoadObservable;
  24504. },
  24505. enumerable: true,
  24506. configurable: true
  24507. });
  24508. Texture.prototype.serialize = function () {
  24509. var serializationObject = _super.prototype.serialize.call(this);
  24510. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  24511. serializationObject.base64String = this._buffer;
  24512. serializationObject.name = serializationObject.name.replace("data:", "");
  24513. }
  24514. return serializationObject;
  24515. };
  24516. Texture.prototype.getClassName = function () {
  24517. return "Texture";
  24518. };
  24519. Texture.prototype.dispose = function () {
  24520. _super.prototype.dispose.call(this);
  24521. if (this.onLoadObservable) {
  24522. this.onLoadObservable.clear();
  24523. this._onLoadObservable = null;
  24524. }
  24525. this._delayedOnLoad = null;
  24526. this._delayedOnError = null;
  24527. };
  24528. // Statics
  24529. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24530. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24531. if (onLoad === void 0) { onLoad = null; }
  24532. if (onError === void 0) { onError = null; }
  24533. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24534. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  24535. };
  24536. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24537. if (parsedTexture.customType) {
  24538. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24539. // Update Sampling Mode
  24540. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  24541. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  24542. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  24543. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  24544. }
  24545. }
  24546. return parsedCustomTexture;
  24547. }
  24548. if (parsedTexture.isCube) {
  24549. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24550. }
  24551. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24552. return null;
  24553. }
  24554. var texture = BABYLON.SerializationHelper.Parse(function () {
  24555. var generateMipMaps = true;
  24556. if (parsedTexture.noMipmap) {
  24557. generateMipMaps = false;
  24558. }
  24559. if (parsedTexture.mirrorPlane) {
  24560. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24561. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24562. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24563. return mirrorTexture;
  24564. }
  24565. else if (parsedTexture.isRenderTarget) {
  24566. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24567. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24568. return renderTargetTexture;
  24569. }
  24570. else {
  24571. var texture;
  24572. if (parsedTexture.base64String) {
  24573. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  24574. }
  24575. else {
  24576. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  24577. }
  24578. return texture;
  24579. }
  24580. }, parsedTexture, scene);
  24581. // Update Sampling Mode
  24582. if (parsedTexture.samplingMode) {
  24583. var sampling = parsedTexture.samplingMode;
  24584. if (texture._samplingMode !== sampling) {
  24585. texture.updateSamplingMode(sampling);
  24586. }
  24587. }
  24588. // Animations
  24589. if (parsedTexture.animations) {
  24590. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24591. var parsedAnimation = parsedTexture.animations[animationIndex];
  24592. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24593. }
  24594. }
  24595. return texture;
  24596. };
  24597. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24598. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24599. if (noMipmap === void 0) { noMipmap = false; }
  24600. if (invertY === void 0) { invertY = true; }
  24601. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24602. if (onLoad === void 0) { onLoad = null; }
  24603. if (onError === void 0) { onError = null; }
  24604. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24605. if (name.substr(0, 5) !== "data:") {
  24606. name = "data:" + name;
  24607. }
  24608. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  24609. };
  24610. // Constants
  24611. Texture.NEAREST_SAMPLINGMODE = 1;
  24612. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  24613. Texture.BILINEAR_SAMPLINGMODE = 2;
  24614. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  24615. Texture.TRILINEAR_SAMPLINGMODE = 3;
  24616. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  24617. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  24618. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  24619. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  24620. Texture.NEAREST_LINEAR = 7;
  24621. Texture.NEAREST_NEAREST = 8;
  24622. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  24623. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  24624. Texture.LINEAR_LINEAR = 11;
  24625. Texture.LINEAR_NEAREST = 12;
  24626. Texture.EXPLICIT_MODE = 0;
  24627. Texture.SPHERICAL_MODE = 1;
  24628. Texture.PLANAR_MODE = 2;
  24629. Texture.CUBIC_MODE = 3;
  24630. Texture.PROJECTION_MODE = 4;
  24631. Texture.SKYBOX_MODE = 5;
  24632. Texture.INVCUBIC_MODE = 6;
  24633. Texture.EQUIRECTANGULAR_MODE = 7;
  24634. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  24635. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  24636. Texture.CLAMP_ADDRESSMODE = 0;
  24637. Texture.WRAP_ADDRESSMODE = 1;
  24638. Texture.MIRROR_ADDRESSMODE = 2;
  24639. __decorate([
  24640. BABYLON.serialize()
  24641. ], Texture.prototype, "url", void 0);
  24642. __decorate([
  24643. BABYLON.serialize()
  24644. ], Texture.prototype, "uOffset", void 0);
  24645. __decorate([
  24646. BABYLON.serialize()
  24647. ], Texture.prototype, "vOffset", void 0);
  24648. __decorate([
  24649. BABYLON.serialize()
  24650. ], Texture.prototype, "uScale", void 0);
  24651. __decorate([
  24652. BABYLON.serialize()
  24653. ], Texture.prototype, "vScale", void 0);
  24654. __decorate([
  24655. BABYLON.serialize()
  24656. ], Texture.prototype, "uAng", void 0);
  24657. __decorate([
  24658. BABYLON.serialize()
  24659. ], Texture.prototype, "vAng", void 0);
  24660. __decorate([
  24661. BABYLON.serialize()
  24662. ], Texture.prototype, "wAng", void 0);
  24663. __decorate([
  24664. BABYLON.serialize()
  24665. ], Texture.prototype, "isBlocking", null);
  24666. return Texture;
  24667. }(BABYLON.BaseTexture));
  24668. BABYLON.Texture = Texture;
  24669. })(BABYLON || (BABYLON = {}));
  24670. //# sourceMappingURL=babylon.texture.js.map
  24671. var BABYLON;
  24672. (function (BABYLON) {
  24673. var _InstancesBatch = /** @class */ (function () {
  24674. function _InstancesBatch() {
  24675. this.mustReturn = false;
  24676. this.visibleInstances = new Array();
  24677. this.renderSelf = new Array();
  24678. }
  24679. return _InstancesBatch;
  24680. }());
  24681. BABYLON._InstancesBatch = _InstancesBatch;
  24682. var Mesh = /** @class */ (function (_super) {
  24683. __extends(Mesh, _super);
  24684. /**
  24685. * @constructor
  24686. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  24687. * @param {Scene} scene The scene to add this mesh to.
  24688. * @param {Node} parent The parent of this mesh, if it has one
  24689. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  24690. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  24691. * When false, achieved by calling a clone(), also passing False.
  24692. * This will make creation of children, recursive.
  24693. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  24694. */
  24695. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  24696. if (scene === void 0) { scene = null; }
  24697. if (parent === void 0) { parent = null; }
  24698. if (source === void 0) { source = null; }
  24699. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24700. var _this = _super.call(this, name, scene) || this;
  24701. // Events
  24702. /**
  24703. * An event triggered before rendering the mesh
  24704. * @type {BABYLON.Observable}
  24705. */
  24706. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24707. /**
  24708. * An event triggered after rendering the mesh
  24709. * @type {BABYLON.Observable}
  24710. */
  24711. _this.onAfterRenderObservable = new BABYLON.Observable();
  24712. /**
  24713. * An event triggered before drawing the mesh
  24714. * @type {BABYLON.Observable}
  24715. */
  24716. _this.onBeforeDrawObservable = new BABYLON.Observable();
  24717. // Members
  24718. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24719. _this.instances = new Array();
  24720. _this._LODLevels = new Array();
  24721. _this._visibleInstances = {};
  24722. _this._renderIdForInstances = new Array();
  24723. _this._batchCache = new _InstancesBatch();
  24724. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  24725. // Use by builder only to know what orientation were the mesh build in.
  24726. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  24727. _this.overrideMaterialSideOrientation = null;
  24728. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  24729. // Will be used to save a source mesh reference, If any
  24730. _this._source = null;
  24731. scene = _this.getScene();
  24732. if (source) {
  24733. // Source mesh
  24734. _this._source = source;
  24735. // Geometry
  24736. if (source._geometry) {
  24737. source._geometry.applyToMesh(_this);
  24738. }
  24739. // Deep copy
  24740. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  24741. // Metadata
  24742. if (source.metadata && source.metadata.clone) {
  24743. _this.metadata = source.metadata.clone();
  24744. }
  24745. else {
  24746. _this.metadata = source.metadata;
  24747. }
  24748. // Tags
  24749. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  24750. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  24751. }
  24752. // Parent
  24753. _this.parent = source.parent;
  24754. // Pivot
  24755. _this.setPivotMatrix(source.getPivotMatrix());
  24756. _this.id = name + "." + source.id;
  24757. // Material
  24758. _this.material = source.material;
  24759. var index;
  24760. if (!doNotCloneChildren) {
  24761. // Children
  24762. var directDescendants = source.getDescendants(true);
  24763. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  24764. var child = directDescendants[index_1];
  24765. if (child.clone) {
  24766. child.clone(name + "." + child.name, _this);
  24767. }
  24768. }
  24769. }
  24770. // Physics clone
  24771. var physicsEngine = _this.getScene().getPhysicsEngine();
  24772. if (clonePhysicsImpostor && physicsEngine) {
  24773. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  24774. if (impostor) {
  24775. _this.physicsImpostor = impostor.clone(_this);
  24776. }
  24777. }
  24778. // Particles
  24779. for (index = 0; index < scene.particleSystems.length; index++) {
  24780. var system = scene.particleSystems[index];
  24781. if (system.emitter === source) {
  24782. system.clone(system.name, _this);
  24783. }
  24784. }
  24785. _this.computeWorldMatrix(true);
  24786. }
  24787. // Parent
  24788. if (parent !== null) {
  24789. _this.parent = parent;
  24790. }
  24791. return _this;
  24792. }
  24793. Object.defineProperty(Mesh, "FRONTSIDE", {
  24794. /**
  24795. * Mesh side orientation : usually the external or front surface
  24796. */
  24797. get: function () {
  24798. return Mesh._FRONTSIDE;
  24799. },
  24800. enumerable: true,
  24801. configurable: true
  24802. });
  24803. Object.defineProperty(Mesh, "BACKSIDE", {
  24804. /**
  24805. * Mesh side orientation : usually the internal or back surface
  24806. */
  24807. get: function () {
  24808. return Mesh._BACKSIDE;
  24809. },
  24810. enumerable: true,
  24811. configurable: true
  24812. });
  24813. Object.defineProperty(Mesh, "DOUBLESIDE", {
  24814. /**
  24815. * Mesh side orientation : both internal and external or front and back surfaces
  24816. */
  24817. get: function () {
  24818. return Mesh._DOUBLESIDE;
  24819. },
  24820. enumerable: true,
  24821. configurable: true
  24822. });
  24823. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  24824. /**
  24825. * Mesh side orientation : by default, `FRONTSIDE`
  24826. */
  24827. get: function () {
  24828. return Mesh._DEFAULTSIDE;
  24829. },
  24830. enumerable: true,
  24831. configurable: true
  24832. });
  24833. Object.defineProperty(Mesh, "NO_CAP", {
  24834. /**
  24835. * Mesh cap setting : no cap
  24836. */
  24837. get: function () {
  24838. return Mesh._NO_CAP;
  24839. },
  24840. enumerable: true,
  24841. configurable: true
  24842. });
  24843. Object.defineProperty(Mesh, "CAP_START", {
  24844. /**
  24845. * Mesh cap setting : one cap at the beginning of the mesh
  24846. */
  24847. get: function () {
  24848. return Mesh._CAP_START;
  24849. },
  24850. enumerable: true,
  24851. configurable: true
  24852. });
  24853. Object.defineProperty(Mesh, "CAP_END", {
  24854. /**
  24855. * Mesh cap setting : one cap at the end of the mesh
  24856. */
  24857. get: function () {
  24858. return Mesh._CAP_END;
  24859. },
  24860. enumerable: true,
  24861. configurable: true
  24862. });
  24863. Object.defineProperty(Mesh, "CAP_ALL", {
  24864. /**
  24865. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  24866. */
  24867. get: function () {
  24868. return Mesh._CAP_ALL;
  24869. },
  24870. enumerable: true,
  24871. configurable: true
  24872. });
  24873. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  24874. set: function (callback) {
  24875. if (this._onBeforeDrawObserver) {
  24876. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  24877. }
  24878. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  24879. },
  24880. enumerable: true,
  24881. configurable: true
  24882. });
  24883. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  24884. get: function () {
  24885. return this._morphTargetManager;
  24886. },
  24887. set: function (value) {
  24888. if (this._morphTargetManager === value) {
  24889. return;
  24890. }
  24891. this._morphTargetManager = value;
  24892. this._syncGeometryWithMorphTargetManager();
  24893. },
  24894. enumerable: true,
  24895. configurable: true
  24896. });
  24897. Object.defineProperty(Mesh.prototype, "source", {
  24898. get: function () {
  24899. return this._source;
  24900. },
  24901. enumerable: true,
  24902. configurable: true
  24903. });
  24904. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  24905. get: function () {
  24906. return this._unIndexed;
  24907. },
  24908. set: function (value) {
  24909. if (this._unIndexed !== value) {
  24910. this._unIndexed = value;
  24911. this._markSubMeshesAsAttributesDirty();
  24912. }
  24913. },
  24914. enumerable: true,
  24915. configurable: true
  24916. });
  24917. // Methods
  24918. /**
  24919. * Returns the string "Mesh".
  24920. */
  24921. Mesh.prototype.getClassName = function () {
  24922. return "Mesh";
  24923. };
  24924. /**
  24925. * Returns a string.
  24926. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24927. */
  24928. Mesh.prototype.toString = function (fullDetails) {
  24929. var ret = _super.prototype.toString.call(this, fullDetails);
  24930. ret += ", n vertices: " + this.getTotalVertices();
  24931. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  24932. if (this.animations) {
  24933. for (var i = 0; i < this.animations.length; i++) {
  24934. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  24935. }
  24936. }
  24937. if (fullDetails) {
  24938. if (this._geometry) {
  24939. var ib = this.getIndices();
  24940. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24941. if (vb && ib) {
  24942. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  24943. }
  24944. }
  24945. else {
  24946. ret += ", flat shading: UNKNOWN";
  24947. }
  24948. }
  24949. return ret;
  24950. };
  24951. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  24952. /**
  24953. * True if the mesh has some Levels Of Details (LOD).
  24954. * Returns a boolean.
  24955. */
  24956. get: function () {
  24957. return this._LODLevels.length > 0;
  24958. },
  24959. enumerable: true,
  24960. configurable: true
  24961. });
  24962. Mesh.prototype._sortLODLevels = function () {
  24963. this._LODLevels.sort(function (a, b) {
  24964. if (a.distance < b.distance) {
  24965. return 1;
  24966. }
  24967. if (a.distance > b.distance) {
  24968. return -1;
  24969. }
  24970. return 0;
  24971. });
  24972. };
  24973. /**
  24974. * Add a mesh as LOD level triggered at the given distance.
  24975. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24976. * @param {number} distance The distance from the center of the object to show this level
  24977. * @param {Mesh} mesh The mesh to be added as LOD level
  24978. * @return {Mesh} This mesh (for chaining)
  24979. */
  24980. Mesh.prototype.addLODLevel = function (distance, mesh) {
  24981. if (mesh && mesh._masterMesh) {
  24982. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  24983. return this;
  24984. }
  24985. var level = new BABYLON.MeshLODLevel(distance, mesh);
  24986. this._LODLevels.push(level);
  24987. if (mesh) {
  24988. mesh._masterMesh = this;
  24989. }
  24990. this._sortLODLevels();
  24991. return this;
  24992. };
  24993. /**
  24994. * Returns the LOD level mesh at the passed distance or null if not found.
  24995. * It is related to the method `addLODLevel(distance, mesh)`.
  24996. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24997. * Returns an object Mesh or `null`.
  24998. */
  24999. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  25000. for (var index = 0; index < this._LODLevels.length; index++) {
  25001. var level = this._LODLevels[index];
  25002. if (level.distance === distance) {
  25003. return level.mesh;
  25004. }
  25005. }
  25006. return null;
  25007. };
  25008. /**
  25009. * Remove a mesh from the LOD array
  25010. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25011. * @param {Mesh} mesh The mesh to be removed.
  25012. * @return {Mesh} This mesh (for chaining)
  25013. */
  25014. Mesh.prototype.removeLODLevel = function (mesh) {
  25015. for (var index = 0; index < this._LODLevels.length; index++) {
  25016. if (this._LODLevels[index].mesh === mesh) {
  25017. this._LODLevels.splice(index, 1);
  25018. if (mesh) {
  25019. mesh._masterMesh = null;
  25020. }
  25021. }
  25022. }
  25023. this._sortLODLevels();
  25024. return this;
  25025. };
  25026. /**
  25027. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  25028. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25029. */
  25030. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  25031. if (!this._LODLevels || this._LODLevels.length === 0) {
  25032. return this;
  25033. }
  25034. var bSphere;
  25035. if (boundingSphere) {
  25036. bSphere = boundingSphere;
  25037. }
  25038. else {
  25039. var boundingInfo = this.getBoundingInfo();
  25040. bSphere = boundingInfo.boundingSphere;
  25041. }
  25042. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  25043. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  25044. if (this.onLODLevelSelection) {
  25045. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  25046. }
  25047. return this;
  25048. }
  25049. for (var index = 0; index < this._LODLevels.length; index++) {
  25050. var level = this._LODLevels[index];
  25051. if (level.distance < distanceToCamera) {
  25052. if (level.mesh) {
  25053. level.mesh._preActivate();
  25054. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  25055. }
  25056. if (this.onLODLevelSelection) {
  25057. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  25058. }
  25059. return level.mesh;
  25060. }
  25061. }
  25062. if (this.onLODLevelSelection) {
  25063. this.onLODLevelSelection(distanceToCamera, this, this);
  25064. }
  25065. return this;
  25066. };
  25067. Object.defineProperty(Mesh.prototype, "geometry", {
  25068. /**
  25069. * Returns the mesh internal Geometry object.
  25070. */
  25071. get: function () {
  25072. return this._geometry;
  25073. },
  25074. enumerable: true,
  25075. configurable: true
  25076. });
  25077. /**
  25078. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  25079. */
  25080. Mesh.prototype.getTotalVertices = function () {
  25081. if (this._geometry === null || this._geometry === undefined) {
  25082. return 0;
  25083. }
  25084. return this._geometry.getTotalVertices();
  25085. };
  25086. /**
  25087. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  25088. * 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.
  25089. * You can force the copy with forceCopy === true
  25090. * Returns null if the mesh has no geometry or no vertex buffer.
  25091. * Possible `kind` values :
  25092. * - BABYLON.VertexBuffer.PositionKind
  25093. * - BABYLON.VertexBuffer.UVKind
  25094. * - BABYLON.VertexBuffer.UV2Kind
  25095. * - BABYLON.VertexBuffer.UV3Kind
  25096. * - BABYLON.VertexBuffer.UV4Kind
  25097. * - BABYLON.VertexBuffer.UV5Kind
  25098. * - BABYLON.VertexBuffer.UV6Kind
  25099. * - BABYLON.VertexBuffer.ColorKind
  25100. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25101. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25102. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25103. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25104. */
  25105. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  25106. if (!this._geometry) {
  25107. return null;
  25108. }
  25109. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  25110. };
  25111. /**
  25112. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  25113. * Returns `null` if the mesh has no geometry.
  25114. * Possible `kind` values :
  25115. * - BABYLON.VertexBuffer.PositionKind
  25116. * - BABYLON.VertexBuffer.UVKind
  25117. * - BABYLON.VertexBuffer.UV2Kind
  25118. * - BABYLON.VertexBuffer.UV3Kind
  25119. * - BABYLON.VertexBuffer.UV4Kind
  25120. * - BABYLON.VertexBuffer.UV5Kind
  25121. * - BABYLON.VertexBuffer.UV6Kind
  25122. * - BABYLON.VertexBuffer.ColorKind
  25123. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25124. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25125. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25126. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25127. */
  25128. Mesh.prototype.getVertexBuffer = function (kind) {
  25129. if (!this._geometry) {
  25130. return null;
  25131. }
  25132. return this._geometry.getVertexBuffer(kind);
  25133. };
  25134. /**
  25135. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  25136. * Possible `kind` values :
  25137. * - BABYLON.VertexBuffer.PositionKind
  25138. * - BABYLON.VertexBuffer.UVKind
  25139. * - BABYLON.VertexBuffer.UV2Kind
  25140. * - BABYLON.VertexBuffer.UV3Kind
  25141. * - BABYLON.VertexBuffer.UV4Kind
  25142. * - BABYLON.VertexBuffer.UV5Kind
  25143. * - BABYLON.VertexBuffer.UV6Kind
  25144. * - BABYLON.VertexBuffer.ColorKind
  25145. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25146. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25147. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25148. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25149. */
  25150. Mesh.prototype.isVerticesDataPresent = function (kind) {
  25151. if (!this._geometry) {
  25152. if (this._delayInfo) {
  25153. return this._delayInfo.indexOf(kind) !== -1;
  25154. }
  25155. return false;
  25156. }
  25157. return this._geometry.isVerticesDataPresent(kind);
  25158. };
  25159. /**
  25160. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  25161. * Possible `kind` values :
  25162. * - BABYLON.VertexBuffer.PositionKind
  25163. * - BABYLON.VertexBuffer.UVKind
  25164. * - BABYLON.VertexBuffer.UV2Kind
  25165. * - BABYLON.VertexBuffer.UV3Kind
  25166. * - BABYLON.VertexBuffer.UV4Kind
  25167. * - BABYLON.VertexBuffer.UV5Kind
  25168. * - BABYLON.VertexBuffer.UV6Kind
  25169. * - BABYLON.VertexBuffer.ColorKind
  25170. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25171. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25172. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25173. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25174. */
  25175. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  25176. if (!this._geometry) {
  25177. if (this._delayInfo) {
  25178. return this._delayInfo.indexOf(kind) !== -1;
  25179. }
  25180. return false;
  25181. }
  25182. return this._geometry.isVertexBufferUpdatable(kind);
  25183. };
  25184. /**
  25185. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  25186. * Possible `kind` values :
  25187. * - BABYLON.VertexBuffer.PositionKind
  25188. * - BABYLON.VertexBuffer.UVKind
  25189. * - BABYLON.VertexBuffer.UV2Kind
  25190. * - BABYLON.VertexBuffer.UV3Kind
  25191. * - BABYLON.VertexBuffer.UV4Kind
  25192. * - BABYLON.VertexBuffer.UV5Kind
  25193. * - BABYLON.VertexBuffer.UV6Kind
  25194. * - BABYLON.VertexBuffer.ColorKind
  25195. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25196. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25197. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25198. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25199. */
  25200. Mesh.prototype.getVerticesDataKinds = function () {
  25201. if (!this._geometry) {
  25202. var result = new Array();
  25203. if (this._delayInfo) {
  25204. this._delayInfo.forEach(function (kind, index, array) {
  25205. result.push(kind);
  25206. });
  25207. }
  25208. return result;
  25209. }
  25210. return this._geometry.getVerticesDataKinds();
  25211. };
  25212. /**
  25213. * Returns a positive integer : the total number of indices in this mesh geometry.
  25214. * Returns zero if the mesh has no geometry.
  25215. */
  25216. Mesh.prototype.getTotalIndices = function () {
  25217. if (!this._geometry) {
  25218. return 0;
  25219. }
  25220. return this._geometry.getTotalIndices();
  25221. };
  25222. /**
  25223. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  25224. * 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.
  25225. * Returns an empty array if the mesh has no geometry.
  25226. */
  25227. Mesh.prototype.getIndices = function (copyWhenShared) {
  25228. if (!this._geometry) {
  25229. return [];
  25230. }
  25231. return this._geometry.getIndices(copyWhenShared);
  25232. };
  25233. Object.defineProperty(Mesh.prototype, "isBlocked", {
  25234. get: function () {
  25235. return this._masterMesh !== null && this._masterMesh !== undefined;
  25236. },
  25237. enumerable: true,
  25238. configurable: true
  25239. });
  25240. /**
  25241. * Determine if the current mesh is ready to be rendered
  25242. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  25243. * @returns true if all associated assets are ready (material, textures, shaders)
  25244. */
  25245. Mesh.prototype.isReady = function (forceInstanceSupport) {
  25246. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  25247. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25248. return false;
  25249. }
  25250. if (!_super.prototype.isReady.call(this)) {
  25251. return false;
  25252. }
  25253. if (!this.subMeshes || this.subMeshes.length === 0) {
  25254. return true;
  25255. }
  25256. var engine = this.getEngine();
  25257. var scene = this.getScene();
  25258. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  25259. this.computeWorldMatrix();
  25260. var mat = this.material || scene.defaultMaterial;
  25261. if (mat) {
  25262. var currentAlphaTestingState = engine.getAlphaTesting();
  25263. if (mat.storeEffectOnSubMeshes) {
  25264. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25265. var subMesh = _a[_i];
  25266. var effectiveMaterial = subMesh.getMaterial();
  25267. if (effectiveMaterial) {
  25268. engine.setAlphaTesting(effectiveMaterial.needAlphaTesting() && !effectiveMaterial.needAlphaBlendingForMesh(this));
  25269. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25270. engine.setAlphaTesting(currentAlphaTestingState);
  25271. return false;
  25272. }
  25273. }
  25274. }
  25275. }
  25276. else {
  25277. engine.setAlphaTesting(mat.needAlphaTesting() && !mat.needAlphaBlendingForMesh(this));
  25278. if (!mat.isReady(this, hardwareInstancedRendering)) {
  25279. engine.setAlphaTesting(currentAlphaTestingState);
  25280. return false;
  25281. }
  25282. }
  25283. engine.setAlphaTesting(currentAlphaTestingState);
  25284. }
  25285. // Shadows
  25286. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  25287. var light = _c[_b];
  25288. var generator = light.getShadowGenerator();
  25289. if (generator) {
  25290. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  25291. var subMesh = _e[_d];
  25292. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  25293. return false;
  25294. }
  25295. }
  25296. }
  25297. }
  25298. // LOD
  25299. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  25300. var lod = _g[_f];
  25301. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  25302. return false;
  25303. }
  25304. }
  25305. return true;
  25306. };
  25307. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  25308. /**
  25309. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  25310. * This property is pertinent only for updatable parametric shapes.
  25311. */
  25312. get: function () {
  25313. return this._areNormalsFrozen;
  25314. },
  25315. enumerable: true,
  25316. configurable: true
  25317. });
  25318. /**
  25319. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25320. * It has no effect at all on other shapes.
  25321. * It prevents the mesh normals from being recomputed on next `positions` array update.
  25322. * Returns the Mesh.
  25323. */
  25324. Mesh.prototype.freezeNormals = function () {
  25325. this._areNormalsFrozen = true;
  25326. return this;
  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 reactivates the mesh normals computation if it was previously frozen.
  25332. * Returns the Mesh.
  25333. */
  25334. Mesh.prototype.unfreezeNormals = function () {
  25335. this._areNormalsFrozen = false;
  25336. return this;
  25337. };
  25338. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  25339. /**
  25340. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  25341. */
  25342. set: function (count) {
  25343. this._overridenInstanceCount = count;
  25344. },
  25345. enumerable: true,
  25346. configurable: true
  25347. });
  25348. // Methods
  25349. Mesh.prototype._preActivate = function () {
  25350. var sceneRenderId = this.getScene().getRenderId();
  25351. if (this._preActivateId === sceneRenderId) {
  25352. return this;
  25353. }
  25354. this._preActivateId = sceneRenderId;
  25355. this._visibleInstances = null;
  25356. return this;
  25357. };
  25358. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  25359. if (this._visibleInstances) {
  25360. this._visibleInstances.intermediateDefaultRenderId = renderId;
  25361. }
  25362. return this;
  25363. };
  25364. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  25365. if (!this._visibleInstances) {
  25366. this._visibleInstances = {};
  25367. this._visibleInstances.defaultRenderId = renderId;
  25368. this._visibleInstances.selfDefaultRenderId = this._renderId;
  25369. }
  25370. if (!this._visibleInstances[renderId]) {
  25371. this._visibleInstances[renderId] = new Array();
  25372. }
  25373. this._visibleInstances[renderId].push(instance);
  25374. return this;
  25375. };
  25376. /**
  25377. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  25378. * This means the mesh underlying bounding box and sphere are recomputed.
  25379. * Returns the Mesh.
  25380. */
  25381. Mesh.prototype.refreshBoundingInfo = function () {
  25382. return this._refreshBoundingInfo(false);
  25383. };
  25384. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  25385. if (this._boundingInfo && this._boundingInfo.isLocked) {
  25386. return this;
  25387. }
  25388. var data = this._getPositionData(applySkeleton);
  25389. if (data) {
  25390. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  25391. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25392. }
  25393. if (this.subMeshes) {
  25394. for (var index = 0; index < this.subMeshes.length; index++) {
  25395. this.subMeshes[index].refreshBoundingInfo();
  25396. }
  25397. }
  25398. this._updateBoundingInfo();
  25399. return this;
  25400. };
  25401. Mesh.prototype._getPositionData = function (applySkeleton) {
  25402. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25403. if (data && applySkeleton && this.skeleton) {
  25404. data = data.slice();
  25405. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25406. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25407. if (matricesWeightsData && matricesIndicesData) {
  25408. var needExtras = this.numBoneInfluencers > 4;
  25409. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25410. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25411. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  25412. var tempVector = BABYLON.Tmp.Vector3[0];
  25413. var finalMatrix = BABYLON.Tmp.Matrix[0];
  25414. var tempMatrix = BABYLON.Tmp.Matrix[1];
  25415. var matWeightIdx = 0;
  25416. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  25417. finalMatrix.reset();
  25418. var inf;
  25419. var weight;
  25420. for (inf = 0; inf < 4; inf++) {
  25421. weight = matricesWeightsData[matWeightIdx + inf];
  25422. if (weight <= 0)
  25423. break;
  25424. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25425. finalMatrix.addToSelf(tempMatrix);
  25426. }
  25427. if (needExtras) {
  25428. for (inf = 0; inf < 4; inf++) {
  25429. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25430. if (weight <= 0)
  25431. break;
  25432. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25433. finalMatrix.addToSelf(tempMatrix);
  25434. }
  25435. }
  25436. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  25437. tempVector.toArray(data, index);
  25438. }
  25439. }
  25440. }
  25441. return data;
  25442. };
  25443. Mesh.prototype._createGlobalSubMesh = function (force) {
  25444. var totalVertices = this.getTotalVertices();
  25445. if (!totalVertices || !this.getIndices()) {
  25446. return null;
  25447. }
  25448. // Check if we need to recreate the submeshes
  25449. if (this.subMeshes && this.subMeshes.length > 0) {
  25450. var ib = this.getIndices();
  25451. if (!ib) {
  25452. return null;
  25453. }
  25454. var totalIndices = ib.length;
  25455. var needToRecreate = false;
  25456. if (force) {
  25457. needToRecreate = true;
  25458. }
  25459. else {
  25460. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25461. var submesh = _a[_i];
  25462. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  25463. needToRecreate = true;
  25464. break;
  25465. }
  25466. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  25467. needToRecreate = true;
  25468. break;
  25469. }
  25470. }
  25471. }
  25472. if (!needToRecreate) {
  25473. return this.subMeshes[0];
  25474. }
  25475. }
  25476. this.releaseSubMeshes();
  25477. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  25478. };
  25479. Mesh.prototype.subdivide = function (count) {
  25480. if (count < 1) {
  25481. return;
  25482. }
  25483. var totalIndices = this.getTotalIndices();
  25484. var subdivisionSize = (totalIndices / count) | 0;
  25485. var offset = 0;
  25486. // Ensure that subdivisionSize is a multiple of 3
  25487. while (subdivisionSize % 3 !== 0) {
  25488. subdivisionSize++;
  25489. }
  25490. this.releaseSubMeshes();
  25491. for (var index = 0; index < count; index++) {
  25492. if (offset >= totalIndices) {
  25493. break;
  25494. }
  25495. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  25496. offset += subdivisionSize;
  25497. }
  25498. this.synchronizeInstances();
  25499. };
  25500. /**
  25501. * Sets the vertex data of the mesh geometry for the requested `kind`.
  25502. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  25503. * The `data` are either a numeric array either a Float32Array.
  25504. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  25505. * 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).
  25506. * Note that a new underlying VertexBuffer object is created each call.
  25507. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  25508. *
  25509. * Possible `kind` values :
  25510. * - BABYLON.VertexBuffer.PositionKind
  25511. * - BABYLON.VertexBuffer.UVKind
  25512. * - BABYLON.VertexBuffer.UV2Kind
  25513. * - BABYLON.VertexBuffer.UV3Kind
  25514. * - BABYLON.VertexBuffer.UV4Kind
  25515. * - BABYLON.VertexBuffer.UV5Kind
  25516. * - BABYLON.VertexBuffer.UV6Kind
  25517. * - BABYLON.VertexBuffer.ColorKind
  25518. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25519. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25520. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25521. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25522. *
  25523. * Returns the Mesh.
  25524. */
  25525. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25526. if (updatable === void 0) { updatable = false; }
  25527. if (!this._geometry) {
  25528. var vertexData = new BABYLON.VertexData();
  25529. vertexData.set(data, kind);
  25530. var scene = this.getScene();
  25531. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25532. }
  25533. else {
  25534. this._geometry.setVerticesData(kind, data, updatable, stride);
  25535. }
  25536. return this;
  25537. };
  25538. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  25539. if (updatable === void 0) { updatable = true; }
  25540. var vb = this.getVertexBuffer(kind);
  25541. if (!vb || vb.isUpdatable() === updatable) {
  25542. return;
  25543. }
  25544. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  25545. };
  25546. /**
  25547. * Sets the mesh VertexBuffer.
  25548. * Returns the Mesh.
  25549. */
  25550. Mesh.prototype.setVerticesBuffer = function (buffer) {
  25551. if (!this._geometry) {
  25552. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  25553. }
  25554. this._geometry.setVerticesBuffer(buffer);
  25555. return this;
  25556. };
  25557. /**
  25558. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  25559. * If the mesh has no geometry, it is simply returned as it is.
  25560. * The `data` are either a numeric array either a Float32Array.
  25561. * No new underlying VertexBuffer object is created.
  25562. * 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.
  25563. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  25564. *
  25565. * Possible `kind` values :
  25566. * - BABYLON.VertexBuffer.PositionKind
  25567. * - BABYLON.VertexBuffer.UVKind
  25568. * - BABYLON.VertexBuffer.UV2Kind
  25569. * - BABYLON.VertexBuffer.UV3Kind
  25570. * - BABYLON.VertexBuffer.UV4Kind
  25571. * - BABYLON.VertexBuffer.UV5Kind
  25572. * - BABYLON.VertexBuffer.UV6Kind
  25573. * - BABYLON.VertexBuffer.ColorKind
  25574. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25575. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25576. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25577. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25578. *
  25579. * Returns the Mesh.
  25580. */
  25581. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  25582. if (!this._geometry) {
  25583. return this;
  25584. }
  25585. if (!makeItUnique) {
  25586. this._geometry.updateVerticesData(kind, data, updateExtends);
  25587. }
  25588. else {
  25589. this.makeGeometryUnique();
  25590. this.updateVerticesData(kind, data, updateExtends, false);
  25591. }
  25592. return this;
  25593. };
  25594. /**
  25595. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  25596. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  25597. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  25598. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  25599. * Returns the Mesh.
  25600. */
  25601. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  25602. if (computeNormals === void 0) { computeNormals = true; }
  25603. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25604. if (!positions) {
  25605. return this;
  25606. }
  25607. positionFunction(positions);
  25608. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25609. if (computeNormals) {
  25610. var indices = this.getIndices();
  25611. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25612. if (!normals) {
  25613. return this;
  25614. }
  25615. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  25616. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25617. }
  25618. return this;
  25619. };
  25620. /**
  25621. * Creates a un-shared specific occurence of the geometry for the mesh.
  25622. * Returns the Mesh.
  25623. */
  25624. Mesh.prototype.makeGeometryUnique = function () {
  25625. if (!this._geometry) {
  25626. return this;
  25627. }
  25628. var oldGeometry = this._geometry;
  25629. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  25630. oldGeometry.releaseForMesh(this, true);
  25631. geometry.applyToMesh(this);
  25632. return this;
  25633. };
  25634. /**
  25635. * Sets the mesh indices.
  25636. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  25637. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  25638. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  25639. * This method creates a new index buffer each call.
  25640. * Returns the Mesh.
  25641. */
  25642. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  25643. if (totalVertices === void 0) { totalVertices = null; }
  25644. if (updatable === void 0) { updatable = false; }
  25645. if (!this._geometry) {
  25646. var vertexData = new BABYLON.VertexData();
  25647. vertexData.indices = indices;
  25648. var scene = this.getScene();
  25649. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25650. }
  25651. else {
  25652. this._geometry.setIndices(indices, totalVertices, updatable);
  25653. }
  25654. return this;
  25655. };
  25656. /**
  25657. * Update the current index buffer
  25658. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  25659. * Returns the Mesh.
  25660. */
  25661. Mesh.prototype.updateIndices = function (indices, offset) {
  25662. if (!this._geometry) {
  25663. return this;
  25664. }
  25665. this._geometry.updateIndices(indices, offset);
  25666. return this;
  25667. };
  25668. /**
  25669. * Invert the geometry to move from a right handed system to a left handed one.
  25670. * Returns the Mesh.
  25671. */
  25672. Mesh.prototype.toLeftHanded = function () {
  25673. if (!this._geometry) {
  25674. return this;
  25675. }
  25676. this._geometry.toLeftHanded();
  25677. return this;
  25678. };
  25679. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  25680. if (!this._geometry) {
  25681. return this;
  25682. }
  25683. var engine = this.getScene().getEngine();
  25684. // Wireframe
  25685. var indexToBind;
  25686. if (this._unIndexed) {
  25687. indexToBind = null;
  25688. }
  25689. else {
  25690. switch (fillMode) {
  25691. case BABYLON.Material.PointFillMode:
  25692. indexToBind = null;
  25693. break;
  25694. case BABYLON.Material.WireFrameFillMode:
  25695. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  25696. break;
  25697. default:
  25698. case BABYLON.Material.TriangleFillMode:
  25699. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  25700. break;
  25701. }
  25702. }
  25703. // VBOs
  25704. this._geometry._bind(effect, indexToBind);
  25705. return this;
  25706. };
  25707. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  25708. if (alternate === void 0) { alternate = false; }
  25709. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25710. return this;
  25711. }
  25712. this.onBeforeDrawObservable.notifyObservers(this);
  25713. var scene = this.getScene();
  25714. var engine = scene.getEngine();
  25715. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  25716. // or triangles as points
  25717. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  25718. }
  25719. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  25720. // Triangles as wireframe
  25721. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  25722. }
  25723. else {
  25724. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  25725. }
  25726. if (scene._isAlternateRenderingEnabled && !alternate) {
  25727. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  25728. if (!effect || !scene.activeCamera) {
  25729. return this;
  25730. }
  25731. scene._switchToAlternateCameraConfiguration(true);
  25732. this._effectiveMaterial.bindView(effect);
  25733. this._effectiveMaterial.bindViewProjection(effect);
  25734. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  25735. this._draw(subMesh, fillMode, instancesCount, true);
  25736. engine.setViewport(scene.activeCamera.viewport);
  25737. scene._switchToAlternateCameraConfiguration(false);
  25738. this._effectiveMaterial.bindView(effect);
  25739. this._effectiveMaterial.bindViewProjection(effect);
  25740. }
  25741. return this;
  25742. };
  25743. /**
  25744. * Registers for this mesh a javascript function called just before the rendering process.
  25745. * This function is passed the current mesh.
  25746. * Return the Mesh.
  25747. */
  25748. Mesh.prototype.registerBeforeRender = function (func) {
  25749. this.onBeforeRenderObservable.add(func);
  25750. return this;
  25751. };
  25752. /**
  25753. * Disposes a previously registered javascript function called before the rendering.
  25754. * This function is passed the current mesh.
  25755. * Returns the Mesh.
  25756. */
  25757. Mesh.prototype.unregisterBeforeRender = function (func) {
  25758. this.onBeforeRenderObservable.removeCallback(func);
  25759. return this;
  25760. };
  25761. /**
  25762. * Registers for this mesh a javascript function called just after the rendering is complete.
  25763. * This function is passed the current mesh.
  25764. * Returns the Mesh.
  25765. */
  25766. Mesh.prototype.registerAfterRender = function (func) {
  25767. this.onAfterRenderObservable.add(func);
  25768. return this;
  25769. };
  25770. /**
  25771. * Disposes a previously registered javascript function called after the rendering.
  25772. * This function is passed the current mesh.
  25773. * Return the Mesh.
  25774. */
  25775. Mesh.prototype.unregisterAfterRender = function (func) {
  25776. this.onAfterRenderObservable.removeCallback(func);
  25777. return this;
  25778. };
  25779. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  25780. var scene = this.getScene();
  25781. this._batchCache.mustReturn = false;
  25782. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  25783. this._batchCache.visibleInstances[subMeshId] = null;
  25784. if (this._visibleInstances) {
  25785. var currentRenderId = scene.getRenderId();
  25786. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  25787. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  25788. var selfRenderId = this._renderId;
  25789. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  25790. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  25791. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  25792. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  25793. }
  25794. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  25795. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  25796. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  25797. this._batchCache.mustReturn = true;
  25798. return this._batchCache;
  25799. }
  25800. if (currentRenderId !== selfRenderId) {
  25801. this._batchCache.renderSelf[subMeshId] = false;
  25802. }
  25803. }
  25804. this._renderIdForInstances[subMeshId] = currentRenderId;
  25805. }
  25806. return this._batchCache;
  25807. };
  25808. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  25809. var visibleInstances = batch.visibleInstances[subMesh._id];
  25810. if (!visibleInstances) {
  25811. return this;
  25812. }
  25813. var matricesCount = visibleInstances.length + 1;
  25814. var bufferSize = matricesCount * 16 * 4;
  25815. var currentInstancesBufferSize = this._instancesBufferSize;
  25816. var instancesBuffer = this._instancesBuffer;
  25817. while (this._instancesBufferSize < bufferSize) {
  25818. this._instancesBufferSize *= 2;
  25819. }
  25820. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  25821. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  25822. }
  25823. var offset = 0;
  25824. var instancesCount = 0;
  25825. var world = this.getWorldMatrix();
  25826. if (batch.renderSelf[subMesh._id]) {
  25827. world.copyToArray(this._instancesData, offset);
  25828. offset += 16;
  25829. instancesCount++;
  25830. }
  25831. if (visibleInstances) {
  25832. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  25833. var instance = visibleInstances[instanceIndex];
  25834. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  25835. offset += 16;
  25836. instancesCount++;
  25837. }
  25838. }
  25839. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  25840. if (instancesBuffer) {
  25841. instancesBuffer.dispose();
  25842. }
  25843. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  25844. this._instancesBuffer = instancesBuffer;
  25845. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  25846. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  25847. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  25848. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  25849. }
  25850. else {
  25851. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  25852. }
  25853. this._bind(subMesh, effect, fillMode);
  25854. this._draw(subMesh, fillMode, instancesCount);
  25855. engine.unbindInstanceAttributes();
  25856. return this;
  25857. };
  25858. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  25859. var scene = this.getScene();
  25860. var engine = scene.getEngine();
  25861. if (hardwareInstancedRendering) {
  25862. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  25863. }
  25864. else {
  25865. if (batch.renderSelf[subMesh._id]) {
  25866. // Draw
  25867. if (onBeforeDraw) {
  25868. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  25869. }
  25870. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  25871. }
  25872. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  25873. if (visibleInstancesForSubMesh) {
  25874. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  25875. var instance = visibleInstancesForSubMesh[instanceIndex];
  25876. // World
  25877. var world = instance.getWorldMatrix();
  25878. if (onBeforeDraw) {
  25879. onBeforeDraw(true, world, effectiveMaterial);
  25880. }
  25881. // Draw
  25882. this._draw(subMesh, fillMode);
  25883. }
  25884. }
  25885. }
  25886. return this;
  25887. };
  25888. /**
  25889. * Triggers the draw call for the mesh.
  25890. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  25891. * Returns the Mesh.
  25892. */
  25893. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  25894. this.checkOcclusionQuery();
  25895. if (this._isOccluded) {
  25896. return this;
  25897. }
  25898. var scene = this.getScene();
  25899. // Managing instances
  25900. var batch = this._getInstancesRenderList(subMesh._id);
  25901. if (batch.mustReturn) {
  25902. return this;
  25903. }
  25904. // Checking geometry state
  25905. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25906. return this;
  25907. }
  25908. this.onBeforeRenderObservable.notifyObservers(this);
  25909. var engine = scene.getEngine();
  25910. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25911. // Material
  25912. var material = subMesh.getMaterial();
  25913. if (!material) {
  25914. return this;
  25915. }
  25916. this._effectiveMaterial = material;
  25917. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25918. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25919. return this;
  25920. }
  25921. }
  25922. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  25923. return this;
  25924. }
  25925. // Alpha mode
  25926. if (enableAlphaMode) {
  25927. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  25928. }
  25929. // Outline - step 1
  25930. var savedDepthWrite = engine.getDepthWrite();
  25931. if (this.renderOutline) {
  25932. engine.setDepthWrite(false);
  25933. scene.getOutlineRenderer().render(subMesh, batch);
  25934. engine.setDepthWrite(savedDepthWrite);
  25935. }
  25936. var effect;
  25937. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25938. effect = subMesh.effect;
  25939. }
  25940. else {
  25941. effect = this._effectiveMaterial.getEffect();
  25942. }
  25943. if (!effect) {
  25944. return this;
  25945. }
  25946. var sideOrientation = this.overrideMaterialSideOrientation;
  25947. if (sideOrientation == null) {
  25948. sideOrientation = this._effectiveMaterial.sideOrientation;
  25949. if (this._getWorldMatrixDeterminant() < 0) {
  25950. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  25951. }
  25952. }
  25953. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  25954. if (this._effectiveMaterial.forceDepthWrite) {
  25955. engine.setDepthWrite(true);
  25956. }
  25957. // Bind
  25958. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  25959. if (!hardwareInstancedRendering) {
  25960. this._bind(subMesh, effect, fillMode);
  25961. }
  25962. var world = this.getWorldMatrix();
  25963. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25964. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  25965. }
  25966. else {
  25967. this._effectiveMaterial.bind(world, this);
  25968. }
  25969. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  25970. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  25971. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25972. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  25973. }
  25974. // Draw
  25975. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25976. // Unbind
  25977. this._effectiveMaterial.unbind();
  25978. // Outline - step 2
  25979. if (this.renderOutline && savedDepthWrite) {
  25980. engine.setDepthWrite(true);
  25981. engine.setColorWrite(false);
  25982. scene.getOutlineRenderer().render(subMesh, batch);
  25983. engine.setColorWrite(true);
  25984. }
  25985. // Overlay
  25986. if (this.renderOverlay) {
  25987. var currentMode = engine.getAlphaMode();
  25988. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25989. scene.getOutlineRenderer().render(subMesh, batch, true);
  25990. engine.setAlphaMode(currentMode);
  25991. }
  25992. this.onAfterRenderObservable.notifyObservers(this);
  25993. return this;
  25994. };
  25995. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  25996. if (isInstance && effectiveMaterial) {
  25997. effectiveMaterial.bindOnlyWorldMatrix(world);
  25998. }
  25999. };
  26000. /**
  26001. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  26002. */
  26003. Mesh.prototype.getEmittedParticleSystems = function () {
  26004. var results = new Array();
  26005. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26006. var particleSystem = this.getScene().particleSystems[index];
  26007. if (particleSystem.emitter === this) {
  26008. results.push(particleSystem);
  26009. }
  26010. }
  26011. return results;
  26012. };
  26013. /**
  26014. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  26015. */
  26016. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  26017. var results = new Array();
  26018. var descendants = this.getDescendants();
  26019. descendants.push(this);
  26020. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26021. var particleSystem = this.getScene().particleSystems[index];
  26022. var emitter = particleSystem.emitter;
  26023. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  26024. results.push(particleSystem);
  26025. }
  26026. }
  26027. return results;
  26028. };
  26029. Mesh.prototype._checkDelayState = function () {
  26030. var scene = this.getScene();
  26031. if (this._geometry) {
  26032. this._geometry.load(scene);
  26033. }
  26034. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26035. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26036. this._queueLoad(scene);
  26037. }
  26038. return this;
  26039. };
  26040. Mesh.prototype._queueLoad = function (scene) {
  26041. var _this = this;
  26042. scene._addPendingData(this);
  26043. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  26044. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26045. if (data instanceof ArrayBuffer) {
  26046. _this._delayLoadingFunction(data, _this);
  26047. }
  26048. else {
  26049. _this._delayLoadingFunction(JSON.parse(data), _this);
  26050. }
  26051. _this.instances.forEach(function (instance) {
  26052. instance._syncSubMeshes();
  26053. });
  26054. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26055. scene._removePendingData(_this);
  26056. }, function () { }, scene.database, getBinaryData);
  26057. return this;
  26058. };
  26059. /**
  26060. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  26061. */
  26062. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  26063. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26064. return false;
  26065. }
  26066. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  26067. return false;
  26068. }
  26069. this._checkDelayState();
  26070. return true;
  26071. };
  26072. /**
  26073. * Sets the mesh material by the material or multiMaterial `id` property.
  26074. * The material `id` is a string identifying the material or the multiMaterial.
  26075. * This method returns the Mesh.
  26076. */
  26077. Mesh.prototype.setMaterialByID = function (id) {
  26078. var materials = this.getScene().materials;
  26079. var index;
  26080. for (index = materials.length - 1; index > -1; index--) {
  26081. if (materials[index].id === id) {
  26082. this.material = materials[index];
  26083. return this;
  26084. }
  26085. }
  26086. // Multi
  26087. var multiMaterials = this.getScene().multiMaterials;
  26088. for (index = multiMaterials.length - 1; index > -1; index--) {
  26089. if (multiMaterials[index].id === id) {
  26090. this.material = multiMaterials[index];
  26091. return this;
  26092. }
  26093. }
  26094. return this;
  26095. };
  26096. /**
  26097. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  26098. */
  26099. Mesh.prototype.getAnimatables = function () {
  26100. var results = new Array();
  26101. if (this.material) {
  26102. results.push(this.material);
  26103. }
  26104. if (this.skeleton) {
  26105. results.push(this.skeleton);
  26106. }
  26107. return results;
  26108. };
  26109. /**
  26110. * Modifies the mesh geometry according to the passed transformation matrix.
  26111. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  26112. * The mesh normals are modified accordingly the same transformation.
  26113. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  26114. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26115. * Returns the Mesh.
  26116. */
  26117. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  26118. // Position
  26119. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26120. return this;
  26121. }
  26122. var submeshes = this.subMeshes.splice(0);
  26123. this._resetPointsArrayCache();
  26124. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26125. var temp = new Array();
  26126. var index;
  26127. for (index = 0; index < data.length; index += 3) {
  26128. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  26129. }
  26130. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  26131. // Normals
  26132. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26133. return this;
  26134. }
  26135. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26136. temp = [];
  26137. for (index = 0; index < data.length; index += 3) {
  26138. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  26139. }
  26140. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  26141. // flip faces?
  26142. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  26143. this.flipFaces();
  26144. }
  26145. // Restore submeshes
  26146. this.releaseSubMeshes();
  26147. this.subMeshes = submeshes;
  26148. return this;
  26149. };
  26150. /**
  26151. * Modifies the mesh geometry according to its own current World Matrix.
  26152. * The mesh World Matrix is then reset.
  26153. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  26154. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  26155. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26156. * Returns the Mesh.
  26157. */
  26158. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  26159. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  26160. this.scaling.copyFromFloats(1, 1, 1);
  26161. this.position.copyFromFloats(0, 0, 0);
  26162. this.rotation.copyFromFloats(0, 0, 0);
  26163. //only if quaternion is already set
  26164. if (this.rotationQuaternion) {
  26165. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  26166. }
  26167. this._worldMatrix = BABYLON.Matrix.Identity();
  26168. return this;
  26169. };
  26170. Object.defineProperty(Mesh.prototype, "_positions", {
  26171. // Cache
  26172. get: function () {
  26173. if (this._geometry) {
  26174. return this._geometry._positions;
  26175. }
  26176. return null;
  26177. },
  26178. enumerable: true,
  26179. configurable: true
  26180. });
  26181. Mesh.prototype._resetPointsArrayCache = function () {
  26182. if (this._geometry) {
  26183. this._geometry._resetPointsArrayCache();
  26184. }
  26185. return this;
  26186. };
  26187. Mesh.prototype._generatePointsArray = function () {
  26188. if (this._geometry) {
  26189. return this._geometry._generatePointsArray();
  26190. }
  26191. return false;
  26192. };
  26193. /**
  26194. * Returns a new Mesh object generated from the current mesh properties.
  26195. * This method must not get confused with createInstance().
  26196. * The parameter `name` is a string, the name given to the new mesh.
  26197. * The optional parameter `newParent` can be any Node object (default `null`).
  26198. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  26199. * 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.
  26200. */
  26201. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  26202. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26203. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  26204. };
  26205. /**
  26206. * Disposes the Mesh.
  26207. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  26208. * Returns nothing.
  26209. */
  26210. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  26211. var _this = this;
  26212. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  26213. this.morphTargetManager = null;
  26214. if (this._geometry) {
  26215. this._geometry.releaseForMesh(this, true);
  26216. }
  26217. // Sources
  26218. var meshes = this.getScene().meshes;
  26219. meshes.forEach(function (abstractMesh) {
  26220. var mesh = abstractMesh;
  26221. if (mesh._source && mesh._source === _this) {
  26222. mesh._source = null;
  26223. }
  26224. });
  26225. this._source = null;
  26226. // Instances
  26227. if (this._instancesBuffer) {
  26228. this._instancesBuffer.dispose();
  26229. this._instancesBuffer = null;
  26230. }
  26231. while (this.instances.length) {
  26232. this.instances[0].dispose();
  26233. }
  26234. // Highlight layers.
  26235. var highlightLayers = this.getScene().highlightLayers;
  26236. for (var i = 0; i < highlightLayers.length; i++) {
  26237. var highlightLayer = highlightLayers[i];
  26238. if (highlightLayer) {
  26239. highlightLayer.removeMesh(this);
  26240. highlightLayer.removeExcludedMesh(this);
  26241. }
  26242. }
  26243. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  26244. };
  26245. /**
  26246. * Modifies the mesh geometry according to a displacement map.
  26247. * 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.
  26248. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26249. * This method returns nothing.
  26250. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  26251. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26252. * 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.
  26253. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26254. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26255. *
  26256. * Returns the Mesh.
  26257. */
  26258. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  26259. var _this = this;
  26260. var scene = this.getScene();
  26261. var onload = function (img) {
  26262. // Getting height map data
  26263. var canvas = document.createElement("canvas");
  26264. var context = canvas.getContext("2d");
  26265. var heightMapWidth = img.width;
  26266. var heightMapHeight = img.height;
  26267. canvas.width = heightMapWidth;
  26268. canvas.height = heightMapHeight;
  26269. context.drawImage(img, 0, 0);
  26270. // Create VertexData from map data
  26271. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26272. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  26273. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  26274. //execute success callback, if set
  26275. if (onSuccess) {
  26276. onSuccess(_this);
  26277. }
  26278. };
  26279. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26280. return this;
  26281. };
  26282. /**
  26283. * Modifies the mesh geometry according to a displacementMap buffer.
  26284. * 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.
  26285. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26286. * This method returns nothing.
  26287. * 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.
  26288. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  26289. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26290. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26291. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26292. *
  26293. * Returns the Mesh.
  26294. */
  26295. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  26296. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  26297. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  26298. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26299. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  26300. return this;
  26301. }
  26302. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26303. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26304. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26305. var position = BABYLON.Vector3.Zero();
  26306. var normal = BABYLON.Vector3.Zero();
  26307. var uv = BABYLON.Vector2.Zero();
  26308. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  26309. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  26310. for (var index = 0; index < positions.length; index += 3) {
  26311. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  26312. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  26313. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  26314. // Compute height
  26315. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  26316. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  26317. var pos = (u + v * heightMapWidth) * 4;
  26318. var r = buffer[pos] / 255.0;
  26319. var g = buffer[pos + 1] / 255.0;
  26320. var b = buffer[pos + 2] / 255.0;
  26321. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26322. normal.normalize();
  26323. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  26324. position = position.add(normal);
  26325. position.toArray(positions, index);
  26326. }
  26327. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  26328. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  26329. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  26330. return this;
  26331. };
  26332. /**
  26333. * Modify the mesh to get a flat shading rendering.
  26334. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  26335. * This method returns the Mesh.
  26336. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  26337. */
  26338. Mesh.prototype.convertToFlatShadedMesh = function () {
  26339. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  26340. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26341. var kinds = this.getVerticesDataKinds();
  26342. var vbs = {};
  26343. var data = {};
  26344. var newdata = {};
  26345. var updatableNormals = false;
  26346. var kindIndex;
  26347. var kind;
  26348. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26349. kind = kinds[kindIndex];
  26350. var vertexBuffer = this.getVertexBuffer(kind);
  26351. if (kind === BABYLON.VertexBuffer.NormalKind) {
  26352. updatableNormals = vertexBuffer.isUpdatable();
  26353. kinds.splice(kindIndex, 1);
  26354. kindIndex--;
  26355. continue;
  26356. }
  26357. vbs[kind] = vertexBuffer;
  26358. data[kind] = vbs[kind].getData();
  26359. newdata[kind] = [];
  26360. }
  26361. // Save previous submeshes
  26362. var previousSubmeshes = this.subMeshes.slice(0);
  26363. var indices = this.getIndices();
  26364. var totalIndices = this.getTotalIndices();
  26365. // Generating unique vertices per face
  26366. var index;
  26367. for (index = 0; index < totalIndices; index++) {
  26368. var vertexIndex = indices[index];
  26369. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26370. kind = kinds[kindIndex];
  26371. var stride = vbs[kind].getStrideSize();
  26372. for (var offset = 0; offset < stride; offset++) {
  26373. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26374. }
  26375. }
  26376. }
  26377. // Updating faces & normal
  26378. var normals = [];
  26379. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  26380. for (index = 0; index < totalIndices; index += 3) {
  26381. indices[index] = index;
  26382. indices[index + 1] = index + 1;
  26383. indices[index + 2] = index + 2;
  26384. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  26385. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  26386. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  26387. var p1p2 = p1.subtract(p2);
  26388. var p3p2 = p3.subtract(p2);
  26389. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  26390. // Store same normals for every vertex
  26391. for (var localIndex = 0; localIndex < 3; localIndex++) {
  26392. normals.push(normal.x);
  26393. normals.push(normal.y);
  26394. normals.push(normal.z);
  26395. }
  26396. }
  26397. this.setIndices(indices);
  26398. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  26399. // Updating vertex buffers
  26400. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26401. kind = kinds[kindIndex];
  26402. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26403. }
  26404. // Updating submeshes
  26405. this.releaseSubMeshes();
  26406. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26407. var previousOne = previousSubmeshes[submeshIndex];
  26408. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26409. }
  26410. this.synchronizeInstances();
  26411. return this;
  26412. };
  26413. /**
  26414. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  26415. * In other words, more vertices, no more indices and a single bigger VBO.
  26416. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  26417. * Returns the Mesh.
  26418. */
  26419. Mesh.prototype.convertToUnIndexedMesh = function () {
  26420. /// <summary>Remove indices by unfolding faces into buffers</summary>
  26421. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26422. var kinds = this.getVerticesDataKinds();
  26423. var vbs = {};
  26424. var data = {};
  26425. var newdata = {};
  26426. var kindIndex;
  26427. var kind;
  26428. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26429. kind = kinds[kindIndex];
  26430. var vertexBuffer = this.getVertexBuffer(kind);
  26431. vbs[kind] = vertexBuffer;
  26432. data[kind] = vbs[kind].getData();
  26433. newdata[kind] = [];
  26434. }
  26435. // Save previous submeshes
  26436. var previousSubmeshes = this.subMeshes.slice(0);
  26437. var indices = this.getIndices();
  26438. var totalIndices = this.getTotalIndices();
  26439. // Generating unique vertices per face
  26440. var index;
  26441. for (index = 0; index < totalIndices; index++) {
  26442. var vertexIndex = indices[index];
  26443. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26444. kind = kinds[kindIndex];
  26445. var stride = vbs[kind].getStrideSize();
  26446. for (var offset = 0; offset < stride; offset++) {
  26447. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26448. }
  26449. }
  26450. }
  26451. // Updating indices
  26452. for (index = 0; index < totalIndices; index += 3) {
  26453. indices[index] = index;
  26454. indices[index + 1] = index + 1;
  26455. indices[index + 2] = index + 2;
  26456. }
  26457. this.setIndices(indices);
  26458. // Updating vertex buffers
  26459. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26460. kind = kinds[kindIndex];
  26461. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26462. }
  26463. // Updating submeshes
  26464. this.releaseSubMeshes();
  26465. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26466. var previousOne = previousSubmeshes[submeshIndex];
  26467. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26468. }
  26469. this._unIndexed = true;
  26470. this.synchronizeInstances();
  26471. return this;
  26472. };
  26473. /**
  26474. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  26475. * This method returns the Mesh.
  26476. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  26477. */
  26478. Mesh.prototype.flipFaces = function (flipNormals) {
  26479. if (flipNormals === void 0) { flipNormals = false; }
  26480. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  26481. var i;
  26482. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  26483. for (i = 0; i < vertex_data.normals.length; i++) {
  26484. vertex_data.normals[i] *= -1;
  26485. }
  26486. }
  26487. if (vertex_data.indices) {
  26488. var temp;
  26489. for (i = 0; i < vertex_data.indices.length; i += 3) {
  26490. // reassign indices
  26491. temp = vertex_data.indices[i + 1];
  26492. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  26493. vertex_data.indices[i + 2] = temp;
  26494. }
  26495. }
  26496. vertex_data.applyToMesh(this);
  26497. return this;
  26498. };
  26499. // Instances
  26500. /**
  26501. * Creates a new InstancedMesh object from the mesh model.
  26502. * An instance shares the same properties and the same material than its model.
  26503. * Only these properties of each instance can then be set individually :
  26504. * - position
  26505. * - rotation
  26506. * - rotationQuaternion
  26507. * - setPivotMatrix
  26508. * - scaling
  26509. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  26510. * Warning : this method is not supported for Line mesh and LineSystem
  26511. */
  26512. Mesh.prototype.createInstance = function (name) {
  26513. return new BABYLON.InstancedMesh(name, this);
  26514. };
  26515. /**
  26516. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  26517. * After this call, all the mesh instances have the same submeshes than the current mesh.
  26518. * This method returns the Mesh.
  26519. */
  26520. Mesh.prototype.synchronizeInstances = function () {
  26521. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  26522. var instance = this.instances[instanceIndex];
  26523. instance._syncSubMeshes();
  26524. }
  26525. return this;
  26526. };
  26527. /**
  26528. * Simplify the mesh according to the given array of settings.
  26529. * Function will return immediately and will simplify async. It returns the Mesh.
  26530. * @param settings a collection of simplification settings.
  26531. * @param parallelProcessing should all levels calculate parallel or one after the other.
  26532. * @param type the type of simplification to run.
  26533. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  26534. */
  26535. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  26536. if (parallelProcessing === void 0) { parallelProcessing = true; }
  26537. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  26538. this.getScene().simplificationQueue.addTask({
  26539. settings: settings,
  26540. parallelProcessing: parallelProcessing,
  26541. mesh: this,
  26542. simplificationType: simplificationType,
  26543. successCallback: successCallback
  26544. });
  26545. return this;
  26546. };
  26547. /**
  26548. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  26549. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  26550. * This should be used together with the simplification to avoid disappearing triangles.
  26551. * Returns the Mesh.
  26552. * @param successCallback an optional success callback to be called after the optimization finished.
  26553. */
  26554. Mesh.prototype.optimizeIndices = function (successCallback) {
  26555. var _this = this;
  26556. var indices = this.getIndices();
  26557. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26558. if (!positions || !indices) {
  26559. return this;
  26560. }
  26561. var vectorPositions = new Array();
  26562. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  26563. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  26564. }
  26565. var dupes = new Array();
  26566. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  26567. var realPos = vectorPositions.length - 1 - iteration;
  26568. var testedPosition = vectorPositions[realPos];
  26569. for (var j = 0; j < realPos; ++j) {
  26570. var againstPosition = vectorPositions[j];
  26571. if (testedPosition.equals(againstPosition)) {
  26572. dupes[realPos] = j;
  26573. break;
  26574. }
  26575. }
  26576. }, function () {
  26577. for (var i = 0; i < indices.length; ++i) {
  26578. indices[i] = dupes[indices[i]] || indices[i];
  26579. }
  26580. //indices are now reordered
  26581. var originalSubMeshes = _this.subMeshes.slice(0);
  26582. _this.setIndices(indices);
  26583. _this.subMeshes = originalSubMeshes;
  26584. if (successCallback) {
  26585. successCallback(_this);
  26586. }
  26587. });
  26588. return this;
  26589. };
  26590. Mesh.prototype.serialize = function (serializationObject) {
  26591. serializationObject.name = this.name;
  26592. serializationObject.id = this.id;
  26593. serializationObject.type = this.getClassName();
  26594. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  26595. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26596. }
  26597. serializationObject.position = this.position.asArray();
  26598. if (this.rotationQuaternion) {
  26599. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  26600. }
  26601. else if (this.rotation) {
  26602. serializationObject.rotation = this.rotation.asArray();
  26603. }
  26604. serializationObject.scaling = this.scaling.asArray();
  26605. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  26606. serializationObject.isEnabled = this.isEnabled(false);
  26607. serializationObject.isVisible = this.isVisible;
  26608. serializationObject.infiniteDistance = this.infiniteDistance;
  26609. serializationObject.pickable = this.isPickable;
  26610. serializationObject.receiveShadows = this.receiveShadows;
  26611. serializationObject.billboardMode = this.billboardMode;
  26612. serializationObject.visibility = this.visibility;
  26613. serializationObject.checkCollisions = this.checkCollisions;
  26614. serializationObject.isBlocker = this.isBlocker;
  26615. // Parent
  26616. if (this.parent) {
  26617. serializationObject.parentId = this.parent.id;
  26618. }
  26619. // Geometry
  26620. serializationObject.isUnIndexed = this.isUnIndexed;
  26621. var geometry = this._geometry;
  26622. if (geometry) {
  26623. var geometryId = geometry.id;
  26624. serializationObject.geometryId = geometryId;
  26625. // SubMeshes
  26626. serializationObject.subMeshes = [];
  26627. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  26628. var subMesh = this.subMeshes[subIndex];
  26629. serializationObject.subMeshes.push({
  26630. materialIndex: subMesh.materialIndex,
  26631. verticesStart: subMesh.verticesStart,
  26632. verticesCount: subMesh.verticesCount,
  26633. indexStart: subMesh.indexStart,
  26634. indexCount: subMesh.indexCount
  26635. });
  26636. }
  26637. }
  26638. // Material
  26639. if (this.material) {
  26640. serializationObject.materialId = this.material.id;
  26641. }
  26642. else {
  26643. this.material = null;
  26644. }
  26645. // Morph targets
  26646. if (this.morphTargetManager) {
  26647. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  26648. }
  26649. // Skeleton
  26650. if (this.skeleton) {
  26651. serializationObject.skeletonId = this.skeleton.id;
  26652. }
  26653. // Physics
  26654. //TODO implement correct serialization for physics impostors.
  26655. var impostor = this.getPhysicsImpostor();
  26656. if (impostor) {
  26657. serializationObject.physicsMass = impostor.getParam("mass");
  26658. serializationObject.physicsFriction = impostor.getParam("friction");
  26659. serializationObject.physicsRestitution = impostor.getParam("mass");
  26660. serializationObject.physicsImpostor = impostor.type;
  26661. }
  26662. // Metadata
  26663. if (this.metadata) {
  26664. serializationObject.metadata = this.metadata;
  26665. }
  26666. // Instances
  26667. serializationObject.instances = [];
  26668. for (var index = 0; index < this.instances.length; index++) {
  26669. var instance = this.instances[index];
  26670. var serializationInstance = {
  26671. name: instance.name,
  26672. id: instance.id,
  26673. position: instance.position.asArray(),
  26674. scaling: instance.scaling.asArray()
  26675. };
  26676. if (instance.rotationQuaternion) {
  26677. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  26678. }
  26679. else if (instance.rotation) {
  26680. serializationInstance.rotation = instance.rotation.asArray();
  26681. }
  26682. serializationObject.instances.push(serializationInstance);
  26683. // Animations
  26684. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  26685. serializationInstance.ranges = instance.serializeAnimationRanges();
  26686. }
  26687. //
  26688. // Animations
  26689. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26690. serializationObject.ranges = this.serializeAnimationRanges();
  26691. // Layer mask
  26692. serializationObject.layerMask = this.layerMask;
  26693. // Alpha
  26694. serializationObject.alphaIndex = this.alphaIndex;
  26695. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  26696. // Overlay
  26697. serializationObject.overlayAlpha = this.overlayAlpha;
  26698. serializationObject.overlayColor = this.overlayColor.asArray();
  26699. serializationObject.renderOverlay = this.renderOverlay;
  26700. // Fog
  26701. serializationObject.applyFog = this.applyFog;
  26702. // Action Manager
  26703. if (this.actionManager) {
  26704. serializationObject.actions = this.actionManager.serialize(this.name);
  26705. }
  26706. };
  26707. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  26708. if (!this.geometry) {
  26709. return;
  26710. }
  26711. this._markSubMeshesAsAttributesDirty();
  26712. var morphTargetManager = this._morphTargetManager;
  26713. if (morphTargetManager && morphTargetManager.vertexCount) {
  26714. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  26715. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  26716. this.morphTargetManager = null;
  26717. return;
  26718. }
  26719. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  26720. var morphTarget = morphTargetManager.getActiveTarget(index);
  26721. var positions = morphTarget.getPositions();
  26722. if (!positions) {
  26723. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  26724. return;
  26725. }
  26726. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  26727. var normals = morphTarget.getNormals();
  26728. if (normals) {
  26729. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  26730. }
  26731. var tangents = morphTarget.getTangents();
  26732. if (tangents) {
  26733. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  26734. }
  26735. }
  26736. }
  26737. else {
  26738. var index = 0;
  26739. // Positions
  26740. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  26741. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  26742. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  26743. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  26744. }
  26745. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  26746. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  26747. }
  26748. index++;
  26749. }
  26750. }
  26751. };
  26752. // Statics
  26753. /**
  26754. * Returns a new Mesh object parsed from the source provided.
  26755. * The parameter `parsedMesh` is the source.
  26756. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  26757. */
  26758. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  26759. var mesh;
  26760. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  26761. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  26762. }
  26763. else {
  26764. mesh = new Mesh(parsedMesh.name, scene);
  26765. }
  26766. mesh.id = parsedMesh.id;
  26767. if (BABYLON.Tags) {
  26768. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  26769. }
  26770. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  26771. if (parsedMesh.metadata !== undefined) {
  26772. mesh.metadata = parsedMesh.metadata;
  26773. }
  26774. if (parsedMesh.rotationQuaternion) {
  26775. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  26776. }
  26777. else if (parsedMesh.rotation) {
  26778. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  26779. }
  26780. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  26781. if (parsedMesh.localMatrix) {
  26782. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  26783. }
  26784. else if (parsedMesh.pivotMatrix) {
  26785. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  26786. }
  26787. mesh.setEnabled(parsedMesh.isEnabled);
  26788. mesh.isVisible = parsedMesh.isVisible;
  26789. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  26790. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  26791. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  26792. if (parsedMesh.applyFog !== undefined) {
  26793. mesh.applyFog = parsedMesh.applyFog;
  26794. }
  26795. if (parsedMesh.pickable !== undefined) {
  26796. mesh.isPickable = parsedMesh.pickable;
  26797. }
  26798. if (parsedMesh.alphaIndex !== undefined) {
  26799. mesh.alphaIndex = parsedMesh.alphaIndex;
  26800. }
  26801. mesh.receiveShadows = parsedMesh.receiveShadows;
  26802. mesh.billboardMode = parsedMesh.billboardMode;
  26803. if (parsedMesh.visibility !== undefined) {
  26804. mesh.visibility = parsedMesh.visibility;
  26805. }
  26806. mesh.checkCollisions = parsedMesh.checkCollisions;
  26807. if (parsedMesh.isBlocker !== undefined) {
  26808. mesh.isBlocker = parsedMesh.isBlocker;
  26809. }
  26810. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  26811. // freezeWorldMatrix
  26812. if (parsedMesh.freezeWorldMatrix) {
  26813. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  26814. }
  26815. // Parent
  26816. if (parsedMesh.parentId) {
  26817. mesh._waitingParentId = parsedMesh.parentId;
  26818. }
  26819. // Actions
  26820. if (parsedMesh.actions !== undefined) {
  26821. mesh._waitingActions = parsedMesh.actions;
  26822. }
  26823. // Overlay
  26824. if (parsedMesh.overlayAlpha !== undefined) {
  26825. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  26826. }
  26827. if (parsedMesh.overlayColor !== undefined) {
  26828. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  26829. }
  26830. if (parsedMesh.renderOverlay !== undefined) {
  26831. mesh.renderOverlay = parsedMesh.renderOverlay;
  26832. }
  26833. // Geometry
  26834. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  26835. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  26836. if (parsedMesh.delayLoadingFile) {
  26837. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26838. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  26839. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  26840. if (parsedMesh._binaryInfo) {
  26841. mesh._binaryInfo = parsedMesh._binaryInfo;
  26842. }
  26843. mesh._delayInfo = [];
  26844. if (parsedMesh.hasUVs) {
  26845. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26846. }
  26847. if (parsedMesh.hasUVs2) {
  26848. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26849. }
  26850. if (parsedMesh.hasUVs3) {
  26851. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26852. }
  26853. if (parsedMesh.hasUVs4) {
  26854. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26855. }
  26856. if (parsedMesh.hasUVs5) {
  26857. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26858. }
  26859. if (parsedMesh.hasUVs6) {
  26860. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26861. }
  26862. if (parsedMesh.hasColors) {
  26863. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26864. }
  26865. if (parsedMesh.hasMatricesIndices) {
  26866. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26867. }
  26868. if (parsedMesh.hasMatricesWeights) {
  26869. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26870. }
  26871. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  26872. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  26873. mesh._checkDelayState();
  26874. }
  26875. }
  26876. else {
  26877. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  26878. }
  26879. // Material
  26880. if (parsedMesh.materialId) {
  26881. mesh.setMaterialByID(parsedMesh.materialId);
  26882. }
  26883. else {
  26884. mesh.material = null;
  26885. }
  26886. // Morph targets
  26887. if (parsedMesh.morphTargetManagerId > -1) {
  26888. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  26889. }
  26890. // Skeleton
  26891. if (parsedMesh.skeletonId > -1) {
  26892. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  26893. if (parsedMesh.numBoneInfluencers) {
  26894. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  26895. }
  26896. }
  26897. // Animations
  26898. if (parsedMesh.animations) {
  26899. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26900. var parsedAnimation = parsedMesh.animations[animationIndex];
  26901. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26902. }
  26903. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  26904. }
  26905. if (parsedMesh.autoAnimate) {
  26906. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  26907. }
  26908. // Layer Mask
  26909. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  26910. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  26911. }
  26912. else {
  26913. mesh.layerMask = 0x0FFFFFFF;
  26914. }
  26915. // Physics
  26916. if (parsedMesh.physicsImpostor) {
  26917. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  26918. mass: parsedMesh.physicsMass,
  26919. friction: parsedMesh.physicsFriction,
  26920. restitution: parsedMesh.physicsRestitution
  26921. }, scene);
  26922. }
  26923. // Instances
  26924. if (parsedMesh.instances) {
  26925. for (var index = 0; index < parsedMesh.instances.length; index++) {
  26926. var parsedInstance = parsedMesh.instances[index];
  26927. var instance = mesh.createInstance(parsedInstance.name);
  26928. if (parsedInstance.id) {
  26929. instance.id = parsedInstance.id;
  26930. }
  26931. if (BABYLON.Tags) {
  26932. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  26933. }
  26934. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  26935. if (parsedInstance.parentId) {
  26936. instance._waitingParentId = parsedInstance.parentId;
  26937. }
  26938. if (parsedInstance.rotationQuaternion) {
  26939. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  26940. }
  26941. else if (parsedInstance.rotation) {
  26942. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  26943. }
  26944. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  26945. instance.checkCollisions = mesh.checkCollisions;
  26946. if (parsedMesh.animations) {
  26947. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26948. parsedAnimation = parsedMesh.animations[animationIndex];
  26949. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26950. }
  26951. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  26952. }
  26953. }
  26954. }
  26955. return mesh;
  26956. };
  26957. /**
  26958. * Creates a ribbon mesh.
  26959. * Please consider using the same method from the MeshBuilder class instead.
  26960. * 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.
  26961. *
  26962. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  26963. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  26964. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  26965. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  26966. * 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.
  26967. * 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.
  26968. * 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
  26969. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26970. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26971. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26972. */
  26973. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  26974. if (closeArray === void 0) { closeArray = false; }
  26975. if (updatable === void 0) { updatable = false; }
  26976. return BABYLON.MeshBuilder.CreateRibbon(name, {
  26977. pathArray: pathArray,
  26978. closeArray: closeArray,
  26979. closePath: closePath,
  26980. offset: offset,
  26981. updatable: updatable,
  26982. sideOrientation: sideOrientation,
  26983. instance: instance
  26984. }, scene);
  26985. };
  26986. /**
  26987. * Creates a plane polygonal mesh. By default, this is a disc.
  26988. * Please consider using the same method from the MeshBuilder class instead.
  26989. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  26990. * 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.
  26991. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26992. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26993. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26994. */
  26995. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  26996. if (scene === void 0) { scene = null; }
  26997. var options = {
  26998. radius: radius,
  26999. tessellation: tessellation,
  27000. sideOrientation: sideOrientation,
  27001. updatable: updatable
  27002. };
  27003. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  27004. };
  27005. /**
  27006. * Creates a box mesh.
  27007. * Please consider using the same method from the MeshBuilder class instead.
  27008. * The parameter `size` sets the size (float) of each box side (default 1).
  27009. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27010. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27011. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27012. */
  27013. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  27014. if (scene === void 0) { scene = null; }
  27015. var options = {
  27016. size: size,
  27017. sideOrientation: sideOrientation,
  27018. updatable: updatable
  27019. };
  27020. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  27021. };
  27022. /**
  27023. * Creates a sphere mesh.
  27024. * Please consider using the same method from the MeshBuilder class instead.
  27025. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  27026. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  27027. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27028. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27029. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27030. */
  27031. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  27032. var options = {
  27033. segments: segments,
  27034. diameterX: diameter,
  27035. diameterY: diameter,
  27036. diameterZ: diameter,
  27037. sideOrientation: sideOrientation,
  27038. updatable: updatable
  27039. };
  27040. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  27041. };
  27042. /**
  27043. * Creates a cylinder or a cone mesh.
  27044. * Please consider using the same method from the MeshBuilder class instead.
  27045. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  27046. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  27047. * 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.
  27048. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  27049. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  27050. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27051. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27052. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27053. */
  27054. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  27055. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  27056. if (scene !== undefined) {
  27057. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  27058. updatable = scene;
  27059. }
  27060. scene = subdivisions;
  27061. subdivisions = 1;
  27062. }
  27063. var options = {
  27064. height: height,
  27065. diameterTop: diameterTop,
  27066. diameterBottom: diameterBottom,
  27067. tessellation: tessellation,
  27068. subdivisions: subdivisions,
  27069. sideOrientation: sideOrientation,
  27070. updatable: updatable
  27071. };
  27072. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  27073. };
  27074. // Torus (Code from SharpDX.org)
  27075. /**
  27076. * Creates a torus mesh.
  27077. * Please consider using the same method from the MeshBuilder class instead.
  27078. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  27079. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  27080. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  27081. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27082. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27083. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27084. */
  27085. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  27086. var options = {
  27087. diameter: diameter,
  27088. thickness: thickness,
  27089. tessellation: tessellation,
  27090. sideOrientation: sideOrientation,
  27091. updatable: updatable
  27092. };
  27093. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  27094. };
  27095. /**
  27096. * Creates a torus knot mesh.
  27097. * Please consider using the same method from the MeshBuilder class instead.
  27098. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  27099. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  27100. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  27101. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  27102. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27103. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27104. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27105. */
  27106. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  27107. var options = {
  27108. radius: radius,
  27109. tube: tube,
  27110. radialSegments: radialSegments,
  27111. tubularSegments: tubularSegments,
  27112. p: p,
  27113. q: q,
  27114. sideOrientation: sideOrientation,
  27115. updatable: updatable
  27116. };
  27117. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  27118. };
  27119. /**
  27120. * Creates a line mesh.
  27121. * Please consider using the same method from the MeshBuilder class instead.
  27122. * 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.
  27123. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27124. * The parameter `points` is an array successive Vector3.
  27125. * 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
  27126. * When updating an instance, remember that only point positions can change, not the number of points.
  27127. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27128. */
  27129. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  27130. if (scene === void 0) { scene = null; }
  27131. if (updatable === void 0) { updatable = false; }
  27132. if (instance === void 0) { instance = null; }
  27133. var options = {
  27134. points: points,
  27135. updatable: updatable,
  27136. instance: instance
  27137. };
  27138. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  27139. };
  27140. /**
  27141. * Creates a dashed line mesh.
  27142. * Please consider using the same method from the MeshBuilder class instead.
  27143. * 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.
  27144. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27145. * The parameter `points` is an array successive Vector3.
  27146. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  27147. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  27148. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  27149. * 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
  27150. * When updating an instance, remember that only point positions can change, not the number of points.
  27151. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27152. */
  27153. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  27154. if (scene === void 0) { scene = null; }
  27155. var options = {
  27156. points: points,
  27157. dashSize: dashSize,
  27158. gapSize: gapSize,
  27159. dashNb: dashNb,
  27160. updatable: updatable,
  27161. instance: instance
  27162. };
  27163. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  27164. };
  27165. /**
  27166. * Creates a polygon mesh.
  27167. * Please consider using the same method from the MeshBuilder class instead.
  27168. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  27169. * 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.
  27170. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27171. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27172. * Remember you can only change the shape positions, not their number when updating a polygon.
  27173. */
  27174. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  27175. var options = {
  27176. shape: shape,
  27177. holes: holes,
  27178. updatable: updatable,
  27179. sideOrientation: sideOrientation
  27180. };
  27181. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  27182. };
  27183. /**
  27184. * Creates an extruded polygon mesh, with depth in the Y direction.
  27185. * Please consider using the same method from the MeshBuilder class instead.
  27186. */
  27187. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  27188. var options = {
  27189. shape: shape,
  27190. holes: holes,
  27191. depth: depth,
  27192. updatable: updatable,
  27193. sideOrientation: sideOrientation
  27194. };
  27195. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  27196. };
  27197. /**
  27198. * Creates an extruded shape mesh.
  27199. * 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.
  27200. * Please consider using the same method from the MeshBuilder class instead.
  27201. *
  27202. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27203. * 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
  27204. * extruded along the Z axis.
  27205. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27206. * 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.
  27207. * The parameter `scale` (float, default 1) is the value to scale the shape.
  27208. * 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
  27209. * 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
  27210. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27211. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27212. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27213. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27214. */
  27215. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  27216. if (scene === void 0) { scene = null; }
  27217. var options = {
  27218. shape: shape,
  27219. path: path,
  27220. scale: scale,
  27221. rotation: rotation,
  27222. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27223. sideOrientation: sideOrientation,
  27224. instance: instance,
  27225. updatable: updatable
  27226. };
  27227. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  27228. };
  27229. /**
  27230. * Creates an custom extruded shape mesh.
  27231. * 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.
  27232. * Please consider using the same method from the MeshBuilder class instead.
  27233. *
  27234. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27235. * 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
  27236. * extruded along the Z axis.
  27237. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27238. * 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
  27239. * and the distance of this point from the begining of the path :
  27240. * ```javascript
  27241. * var rotationFunction = function(i, distance) {
  27242. * // do things
  27243. * return rotationValue; }
  27244. * ```
  27245. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  27246. * 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
  27247. * and the distance of this point from the begining of the path :
  27248. * ```javascript
  27249. * var scaleFunction = function(i, distance) {
  27250. * // do things
  27251. * return scaleValue;}
  27252. * ```
  27253. * It must returns a float value that will be the scale value applied to the shape on each path point.
  27254. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  27255. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  27256. * 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
  27257. * 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
  27258. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27259. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27260. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27261. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27262. */
  27263. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  27264. var options = {
  27265. shape: shape,
  27266. path: path,
  27267. scaleFunction: scaleFunction,
  27268. rotationFunction: rotationFunction,
  27269. ribbonCloseArray: ribbonCloseArray,
  27270. ribbonClosePath: ribbonClosePath,
  27271. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27272. sideOrientation: sideOrientation,
  27273. instance: instance,
  27274. updatable: updatable
  27275. };
  27276. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  27277. };
  27278. /**
  27279. * Creates lathe mesh.
  27280. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  27281. * Please consider using the same method from the MeshBuilder class instead.
  27282. * 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
  27283. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  27284. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  27285. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  27286. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27287. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27288. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27289. */
  27290. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  27291. var options = {
  27292. shape: shape,
  27293. radius: radius,
  27294. tessellation: tessellation,
  27295. sideOrientation: sideOrientation,
  27296. updatable: updatable
  27297. };
  27298. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  27299. };
  27300. /**
  27301. * Creates a plane mesh.
  27302. * Please consider using the same method from the MeshBuilder class instead.
  27303. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  27304. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27305. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27306. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27307. */
  27308. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  27309. var options = {
  27310. size: size,
  27311. width: size,
  27312. height: size,
  27313. sideOrientation: sideOrientation,
  27314. updatable: updatable
  27315. };
  27316. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  27317. };
  27318. /**
  27319. * Creates a ground mesh.
  27320. * Please consider using the same method from the MeshBuilder class instead.
  27321. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  27322. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  27323. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27324. */
  27325. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  27326. var options = {
  27327. width: width,
  27328. height: height,
  27329. subdivisions: subdivisions,
  27330. updatable: updatable
  27331. };
  27332. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  27333. };
  27334. /**
  27335. * Creates a tiled ground mesh.
  27336. * Please consider using the same method from the MeshBuilder class instead.
  27337. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  27338. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  27339. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  27340. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  27341. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  27342. * numbers of subdivisions on the ground width and height of each tile.
  27343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27344. */
  27345. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  27346. var options = {
  27347. xmin: xmin,
  27348. zmin: zmin,
  27349. xmax: xmax,
  27350. zmax: zmax,
  27351. subdivisions: subdivisions,
  27352. precision: precision,
  27353. updatable: updatable
  27354. };
  27355. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  27356. };
  27357. /**
  27358. * Creates a ground mesh from a height map.
  27359. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  27360. * Please consider using the same method from the MeshBuilder class instead.
  27361. * The parameter `url` sets the URL of the height map image resource.
  27362. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  27363. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  27364. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  27365. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  27366. * 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).
  27367. * This function is passed the newly built mesh :
  27368. * ```javascript
  27369. * function(mesh) { // do things
  27370. * return; }
  27371. * ```
  27372. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27373. */
  27374. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  27375. var options = {
  27376. width: width,
  27377. height: height,
  27378. subdivisions: subdivisions,
  27379. minHeight: minHeight,
  27380. maxHeight: maxHeight,
  27381. updatable: updatable,
  27382. onReady: onReady
  27383. };
  27384. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  27385. };
  27386. /**
  27387. * Creates a tube mesh.
  27388. * 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.
  27389. * Please consider using the same method from the MeshBuilder class instead.
  27390. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  27391. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  27392. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  27393. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  27394. * 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.
  27395. * It must return a radius value (positive float) :
  27396. * ```javascript
  27397. * var radiusFunction = function(i, distance) {
  27398. * // do things
  27399. * return radius; }
  27400. * ```
  27401. * 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
  27402. * 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
  27403. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27404. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27405. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27406. */
  27407. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  27408. var options = {
  27409. path: path,
  27410. radius: radius,
  27411. tessellation: tessellation,
  27412. radiusFunction: radiusFunction,
  27413. arc: 1,
  27414. cap: cap,
  27415. updatable: updatable,
  27416. sideOrientation: sideOrientation,
  27417. instance: instance
  27418. };
  27419. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  27420. };
  27421. /**
  27422. * Creates a polyhedron mesh.
  27423. * Please consider using the same method from the MeshBuilder class instead.
  27424. * 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
  27425. * to choose the wanted type.
  27426. * The parameter `size` (positive float, default 1) sets the polygon size.
  27427. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  27428. * 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`.
  27429. * 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
  27430. * 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)`).
  27431. * 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
  27432. * 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.
  27433. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27434. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27435. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27436. */
  27437. Mesh.CreatePolyhedron = function (name, options, scene) {
  27438. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  27439. };
  27440. /**
  27441. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  27442. * Please consider using the same method from the MeshBuilder class instead.
  27443. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  27444. * 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`).
  27445. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  27446. * 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.
  27447. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27448. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27449. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27450. */
  27451. Mesh.CreateIcoSphere = function (name, options, scene) {
  27452. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  27453. };
  27454. /**
  27455. * Creates a decal mesh.
  27456. * Please consider using the same method from the MeshBuilder class instead.
  27457. * 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.
  27458. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  27459. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  27460. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  27461. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  27462. */
  27463. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  27464. var options = {
  27465. position: position,
  27466. normal: normal,
  27467. size: size,
  27468. angle: angle
  27469. };
  27470. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  27471. };
  27472. // Skeletons
  27473. /**
  27474. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27475. */
  27476. Mesh.prototype.setPositionsForCPUSkinning = function () {
  27477. if (!this._sourcePositions) {
  27478. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27479. if (!source) {
  27480. return this._sourcePositions;
  27481. }
  27482. this._sourcePositions = new Float32Array(source);
  27483. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  27484. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  27485. }
  27486. }
  27487. return this._sourcePositions;
  27488. };
  27489. /**
  27490. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27491. */
  27492. Mesh.prototype.setNormalsForCPUSkinning = function () {
  27493. if (!this._sourceNormals) {
  27494. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27495. if (!source) {
  27496. return this._sourceNormals;
  27497. }
  27498. this._sourceNormals = new Float32Array(source);
  27499. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  27500. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  27501. }
  27502. }
  27503. return this._sourceNormals;
  27504. };
  27505. /**
  27506. * Updates the vertex buffer by applying transformation from the bones.
  27507. * Returns the Mesh.
  27508. *
  27509. * @param {skeleton} skeleton to apply
  27510. */
  27511. Mesh.prototype.applySkeleton = function (skeleton) {
  27512. if (!this.geometry) {
  27513. return this;
  27514. }
  27515. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  27516. return this;
  27517. }
  27518. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  27519. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27520. return this;
  27521. }
  27522. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27523. return this;
  27524. }
  27525. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27526. return this;
  27527. }
  27528. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27529. return this;
  27530. }
  27531. if (!this._sourcePositions) {
  27532. var submeshes = this.subMeshes.slice();
  27533. this.setPositionsForCPUSkinning();
  27534. this.subMeshes = submeshes;
  27535. }
  27536. if (!this._sourceNormals) {
  27537. this.setNormalsForCPUSkinning();
  27538. }
  27539. // positionsData checks for not being Float32Array will only pass at most once
  27540. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27541. if (!positionsData) {
  27542. return this;
  27543. }
  27544. if (!(positionsData instanceof Float32Array)) {
  27545. positionsData = new Float32Array(positionsData);
  27546. }
  27547. // normalsData checks for not being Float32Array will only pass at most once
  27548. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27549. if (!normalsData) {
  27550. return this;
  27551. }
  27552. if (!(normalsData instanceof Float32Array)) {
  27553. normalsData = new Float32Array(normalsData);
  27554. }
  27555. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27556. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27557. if (!matricesWeightsData || !matricesIndicesData) {
  27558. return this;
  27559. }
  27560. var needExtras = this.numBoneInfluencers > 4;
  27561. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27562. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27563. var skeletonMatrices = skeleton.getTransformMatrices(this);
  27564. var tempVector3 = BABYLON.Vector3.Zero();
  27565. var finalMatrix = new BABYLON.Matrix();
  27566. var tempMatrix = new BABYLON.Matrix();
  27567. var matWeightIdx = 0;
  27568. var inf;
  27569. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  27570. var weight;
  27571. for (inf = 0; inf < 4; inf++) {
  27572. weight = matricesWeightsData[matWeightIdx + inf];
  27573. if (weight > 0) {
  27574. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27575. finalMatrix.addToSelf(tempMatrix);
  27576. }
  27577. else
  27578. break;
  27579. }
  27580. if (needExtras) {
  27581. for (inf = 0; inf < 4; inf++) {
  27582. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27583. if (weight > 0) {
  27584. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27585. finalMatrix.addToSelf(tempMatrix);
  27586. }
  27587. else
  27588. break;
  27589. }
  27590. }
  27591. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  27592. tempVector3.toArray(positionsData, index);
  27593. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  27594. tempVector3.toArray(normalsData, index);
  27595. finalMatrix.reset();
  27596. }
  27597. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  27598. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  27599. return this;
  27600. };
  27601. // Tools
  27602. /**
  27603. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  27604. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  27605. */
  27606. Mesh.MinMax = function (meshes) {
  27607. var minVector = null;
  27608. var maxVector = null;
  27609. meshes.forEach(function (mesh, index, array) {
  27610. var boundingInfo = mesh.getBoundingInfo();
  27611. var boundingBox = boundingInfo.boundingBox;
  27612. if (!minVector || !maxVector) {
  27613. minVector = boundingBox.minimumWorld;
  27614. maxVector = boundingBox.maximumWorld;
  27615. }
  27616. else {
  27617. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  27618. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  27619. }
  27620. });
  27621. if (!minVector || !maxVector) {
  27622. return {
  27623. min: BABYLON.Vector3.Zero(),
  27624. max: BABYLON.Vector3.Zero()
  27625. };
  27626. }
  27627. return {
  27628. min: minVector,
  27629. max: maxVector
  27630. };
  27631. };
  27632. /**
  27633. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  27634. */
  27635. Mesh.Center = function (meshesOrMinMaxVector) {
  27636. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  27637. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  27638. };
  27639. /**
  27640. * Merge the array of meshes into a single mesh for performance reasons.
  27641. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  27642. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  27643. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  27644. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  27645. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  27646. */
  27647. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  27648. if (disposeSource === void 0) { disposeSource = true; }
  27649. var index;
  27650. if (!allow32BitsIndices) {
  27651. var totalVertices = 0;
  27652. // Counting vertices
  27653. for (index = 0; index < meshes.length; index++) {
  27654. if (meshes[index]) {
  27655. totalVertices += meshes[index].getTotalVertices();
  27656. if (totalVertices > 65536) {
  27657. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  27658. return null;
  27659. }
  27660. }
  27661. }
  27662. }
  27663. // Merge
  27664. var vertexData = null;
  27665. var otherVertexData;
  27666. var indiceArray = new Array();
  27667. var source = null;
  27668. for (index = 0; index < meshes.length; index++) {
  27669. if (meshes[index]) {
  27670. meshes[index].computeWorldMatrix(true);
  27671. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  27672. otherVertexData.transform(meshes[index].getWorldMatrix());
  27673. if (vertexData) {
  27674. vertexData.merge(otherVertexData);
  27675. }
  27676. else {
  27677. vertexData = otherVertexData;
  27678. source = meshes[index];
  27679. }
  27680. if (subdivideWithSubMeshes) {
  27681. indiceArray.push(meshes[index].getTotalIndices());
  27682. }
  27683. }
  27684. }
  27685. source = source;
  27686. if (!meshSubclass) {
  27687. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  27688. }
  27689. vertexData.applyToMesh(meshSubclass);
  27690. // Setting properties
  27691. meshSubclass.material = source.material;
  27692. meshSubclass.checkCollisions = source.checkCollisions;
  27693. // Cleaning
  27694. if (disposeSource) {
  27695. for (index = 0; index < meshes.length; index++) {
  27696. if (meshes[index]) {
  27697. meshes[index].dispose();
  27698. }
  27699. }
  27700. }
  27701. // Subdivide
  27702. if (subdivideWithSubMeshes) {
  27703. //-- Suppresions du submesh global
  27704. meshSubclass.releaseSubMeshes();
  27705. index = 0;
  27706. var offset = 0;
  27707. //-- aplique la subdivision en fonction du tableau d'indices
  27708. while (index < indiceArray.length) {
  27709. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  27710. offset += indiceArray[index];
  27711. index++;
  27712. }
  27713. }
  27714. return meshSubclass;
  27715. };
  27716. // Consts
  27717. Mesh._FRONTSIDE = 0;
  27718. Mesh._BACKSIDE = 1;
  27719. Mesh._DOUBLESIDE = 2;
  27720. Mesh._DEFAULTSIDE = 0;
  27721. Mesh._NO_CAP = 0;
  27722. Mesh._CAP_START = 1;
  27723. Mesh._CAP_END = 2;
  27724. Mesh._CAP_ALL = 3;
  27725. return Mesh;
  27726. }(BABYLON.AbstractMesh));
  27727. BABYLON.Mesh = Mesh;
  27728. })(BABYLON || (BABYLON = {}));
  27729. //# sourceMappingURL=babylon.mesh.js.map
  27730. var BABYLON;
  27731. (function (BABYLON) {
  27732. var BaseSubMesh = /** @class */ (function () {
  27733. function BaseSubMesh() {
  27734. }
  27735. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  27736. get: function () {
  27737. return this._materialEffect;
  27738. },
  27739. enumerable: true,
  27740. configurable: true
  27741. });
  27742. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  27743. if (defines === void 0) { defines = null; }
  27744. if (this._materialEffect === effect) {
  27745. if (!effect) {
  27746. this._materialDefines = null;
  27747. }
  27748. return;
  27749. }
  27750. this._materialDefines = defines;
  27751. this._materialEffect = effect;
  27752. };
  27753. return BaseSubMesh;
  27754. }());
  27755. BABYLON.BaseSubMesh = BaseSubMesh;
  27756. var SubMesh = /** @class */ (function (_super) {
  27757. __extends(SubMesh, _super);
  27758. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27759. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27760. var _this = _super.call(this) || this;
  27761. _this.materialIndex = materialIndex;
  27762. _this.verticesStart = verticesStart;
  27763. _this.verticesCount = verticesCount;
  27764. _this.indexStart = indexStart;
  27765. _this.indexCount = indexCount;
  27766. _this._renderId = 0;
  27767. _this._mesh = mesh;
  27768. _this._renderingMesh = renderingMesh || mesh;
  27769. mesh.subMeshes.push(_this);
  27770. _this._trianglePlanes = [];
  27771. _this._id = mesh.subMeshes.length - 1;
  27772. if (createBoundingBox) {
  27773. _this.refreshBoundingInfo();
  27774. mesh.computeWorldMatrix(true);
  27775. }
  27776. return _this;
  27777. }
  27778. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27779. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27780. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  27781. };
  27782. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  27783. get: function () {
  27784. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  27785. },
  27786. enumerable: true,
  27787. configurable: true
  27788. });
  27789. /**
  27790. * Returns the submesh BoudingInfo object.
  27791. */
  27792. SubMesh.prototype.getBoundingInfo = function () {
  27793. if (this.IsGlobal) {
  27794. return this._mesh.getBoundingInfo();
  27795. }
  27796. return this._boundingInfo;
  27797. };
  27798. /**
  27799. * Sets the submesh BoundingInfo.
  27800. * Return the SubMesh.
  27801. */
  27802. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  27803. this._boundingInfo = boundingInfo;
  27804. return this;
  27805. };
  27806. /**
  27807. * Returns the mesh of the current submesh.
  27808. */
  27809. SubMesh.prototype.getMesh = function () {
  27810. return this._mesh;
  27811. };
  27812. /**
  27813. * Returns the rendering mesh of the submesh.
  27814. */
  27815. SubMesh.prototype.getRenderingMesh = function () {
  27816. return this._renderingMesh;
  27817. };
  27818. /**
  27819. * Returns the submesh material.
  27820. */
  27821. SubMesh.prototype.getMaterial = function () {
  27822. var rootMaterial = this._renderingMesh.material;
  27823. if (rootMaterial === null || rootMaterial === undefined) {
  27824. return this._mesh.getScene().defaultMaterial;
  27825. }
  27826. else if (rootMaterial.getSubMaterial) {
  27827. var multiMaterial = rootMaterial;
  27828. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  27829. if (this._currentMaterial !== effectiveMaterial) {
  27830. this._currentMaterial = effectiveMaterial;
  27831. this._materialDefines = null;
  27832. }
  27833. return effectiveMaterial;
  27834. }
  27835. return rootMaterial;
  27836. };
  27837. // Methods
  27838. /**
  27839. * Sets a new updated BoundingInfo object to the submesh.
  27840. * Returns the SubMesh.
  27841. */
  27842. SubMesh.prototype.refreshBoundingInfo = function () {
  27843. this._lastColliderWorldVertices = null;
  27844. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  27845. return this;
  27846. }
  27847. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27848. if (!data) {
  27849. this._boundingInfo = this._mesh.getBoundingInfo();
  27850. return this;
  27851. }
  27852. var indices = this._renderingMesh.getIndices();
  27853. var extend;
  27854. //is this the only submesh?
  27855. if (this.indexStart === 0 && this.indexCount === indices.length) {
  27856. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27857. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  27858. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  27859. }
  27860. else {
  27861. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  27862. }
  27863. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27864. return this;
  27865. };
  27866. SubMesh.prototype._checkCollision = function (collider) {
  27867. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27868. return boundingInfo._checkCollision(collider);
  27869. };
  27870. /**
  27871. * Updates the submesh BoundingInfo.
  27872. * Returns the Submesh.
  27873. */
  27874. SubMesh.prototype.updateBoundingInfo = function (world) {
  27875. var boundingInfo = this.getBoundingInfo();
  27876. if (!boundingInfo) {
  27877. this.refreshBoundingInfo();
  27878. boundingInfo = this.getBoundingInfo();
  27879. }
  27880. boundingInfo.update(world);
  27881. return this;
  27882. };
  27883. /**
  27884. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  27885. * Boolean returned.
  27886. */
  27887. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  27888. var boundingInfo = this.getBoundingInfo();
  27889. if (!boundingInfo) {
  27890. return false;
  27891. }
  27892. return boundingInfo.isInFrustum(frustumPlanes);
  27893. };
  27894. /**
  27895. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  27896. * Boolean returned.
  27897. */
  27898. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  27899. var boundingInfo = this.getBoundingInfo();
  27900. if (!boundingInfo) {
  27901. return false;
  27902. }
  27903. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  27904. };
  27905. /**
  27906. * Renders the submesh.
  27907. * Returns it.
  27908. */
  27909. SubMesh.prototype.render = function (enableAlphaMode) {
  27910. this._renderingMesh.render(this, enableAlphaMode);
  27911. return this;
  27912. };
  27913. /**
  27914. * Returns a new Index Buffer.
  27915. * Type returned : WebGLBuffer.
  27916. */
  27917. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  27918. if (!this._linesIndexBuffer) {
  27919. var linesIndices = [];
  27920. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27921. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  27922. }
  27923. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  27924. this.linesIndexCount = linesIndices.length;
  27925. }
  27926. return this._linesIndexBuffer;
  27927. };
  27928. /**
  27929. * True is the passed Ray intersects the submesh bounding box.
  27930. * Boolean returned.
  27931. */
  27932. SubMesh.prototype.canIntersects = function (ray) {
  27933. var boundingInfo = this.getBoundingInfo();
  27934. if (!boundingInfo) {
  27935. return false;
  27936. }
  27937. return ray.intersectsBox(boundingInfo.boundingBox);
  27938. };
  27939. /**
  27940. * Returns an object IntersectionInfo.
  27941. */
  27942. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  27943. var intersectInfo = null;
  27944. // LineMesh first as it's also a Mesh...
  27945. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  27946. var lineMesh = this._mesh;
  27947. // Line test
  27948. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  27949. var p0 = positions[indices[index]];
  27950. var p1 = positions[indices[index + 1]];
  27951. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  27952. if (length < 0) {
  27953. continue;
  27954. }
  27955. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  27956. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  27957. if (fastCheck) {
  27958. break;
  27959. }
  27960. }
  27961. }
  27962. }
  27963. else {
  27964. // Triangles test
  27965. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27966. var p0 = positions[indices[index]];
  27967. var p1 = positions[indices[index + 1]];
  27968. var p2 = positions[indices[index + 2]];
  27969. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  27970. if (currentIntersectInfo) {
  27971. if (currentIntersectInfo.distance < 0) {
  27972. continue;
  27973. }
  27974. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  27975. intersectInfo = currentIntersectInfo;
  27976. intersectInfo.faceId = index / 3;
  27977. if (fastCheck) {
  27978. break;
  27979. }
  27980. }
  27981. }
  27982. }
  27983. }
  27984. return intersectInfo;
  27985. };
  27986. SubMesh.prototype._rebuild = function () {
  27987. if (this._linesIndexBuffer) {
  27988. this._linesIndexBuffer = null;
  27989. }
  27990. };
  27991. // Clone
  27992. /**
  27993. * Creates a new Submesh from the passed Mesh.
  27994. */
  27995. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  27996. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  27997. if (!this.IsGlobal) {
  27998. var boundingInfo = this.getBoundingInfo();
  27999. if (!boundingInfo) {
  28000. return result;
  28001. }
  28002. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  28003. }
  28004. return result;
  28005. };
  28006. // Dispose
  28007. /**
  28008. * Disposes the Submesh.
  28009. * Returns nothing.
  28010. */
  28011. SubMesh.prototype.dispose = function () {
  28012. if (this._linesIndexBuffer) {
  28013. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  28014. this._linesIndexBuffer = null;
  28015. }
  28016. // Remove from mesh
  28017. var index = this._mesh.subMeshes.indexOf(this);
  28018. this._mesh.subMeshes.splice(index, 1);
  28019. };
  28020. // Statics
  28021. /**
  28022. * Creates a new Submesh from the passed parameters :
  28023. * - materialIndex (integer) : the index of the main mesh material.
  28024. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  28025. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  28026. * - mesh (Mesh) : the main mesh to create the submesh from.
  28027. * - renderingMesh (optional Mesh) : rendering mesh.
  28028. */
  28029. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  28030. var minVertexIndex = Number.MAX_VALUE;
  28031. var maxVertexIndex = -Number.MAX_VALUE;
  28032. renderingMesh = (renderingMesh || mesh);
  28033. var indices = renderingMesh.getIndices();
  28034. for (var index = startIndex; index < startIndex + indexCount; index++) {
  28035. var vertexIndex = indices[index];
  28036. if (vertexIndex < minVertexIndex)
  28037. minVertexIndex = vertexIndex;
  28038. if (vertexIndex > maxVertexIndex)
  28039. maxVertexIndex = vertexIndex;
  28040. }
  28041. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  28042. };
  28043. return SubMesh;
  28044. }(BaseSubMesh));
  28045. BABYLON.SubMesh = SubMesh;
  28046. })(BABYLON || (BABYLON = {}));
  28047. //# sourceMappingURL=babylon.subMesh.js.map
  28048. var __assign = (this && this.__assign) || Object.assign || function(t) {
  28049. for (var s, i = 1, n = arguments.length; i < n; i++) {
  28050. s = arguments[i];
  28051. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  28052. t[p] = s[p];
  28053. }
  28054. return t;
  28055. };
  28056. var BABYLON;
  28057. (function (BABYLON) {
  28058. var MaterialDefines = /** @class */ (function () {
  28059. function MaterialDefines() {
  28060. this._isDirty = true;
  28061. this._areLightsDirty = true;
  28062. this._areAttributesDirty = true;
  28063. this._areTexturesDirty = true;
  28064. this._areFresnelDirty = true;
  28065. this._areMiscDirty = true;
  28066. this._areImageProcessingDirty = true;
  28067. this._normals = false;
  28068. this._uvs = false;
  28069. this._needNormals = false;
  28070. this._needUVs = false;
  28071. }
  28072. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  28073. get: function () {
  28074. return this._isDirty;
  28075. },
  28076. enumerable: true,
  28077. configurable: true
  28078. });
  28079. MaterialDefines.prototype.markAsProcessed = function () {
  28080. this._isDirty = false;
  28081. this._areAttributesDirty = false;
  28082. this._areTexturesDirty = false;
  28083. this._areFresnelDirty = false;
  28084. this._areLightsDirty = false;
  28085. this._areMiscDirty = false;
  28086. this._areImageProcessingDirty = false;
  28087. };
  28088. MaterialDefines.prototype.markAsUnprocessed = function () {
  28089. this._isDirty = true;
  28090. };
  28091. MaterialDefines.prototype.markAllAsDirty = function () {
  28092. this._areTexturesDirty = true;
  28093. this._areAttributesDirty = true;
  28094. this._areLightsDirty = true;
  28095. this._areFresnelDirty = true;
  28096. this._areMiscDirty = true;
  28097. this._areImageProcessingDirty = true;
  28098. this._isDirty = true;
  28099. };
  28100. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  28101. this._areImageProcessingDirty = true;
  28102. this._isDirty = true;
  28103. };
  28104. MaterialDefines.prototype.markAsLightDirty = function () {
  28105. this._areLightsDirty = true;
  28106. this._isDirty = true;
  28107. };
  28108. MaterialDefines.prototype.markAsAttributesDirty = function () {
  28109. this._areAttributesDirty = true;
  28110. this._isDirty = true;
  28111. };
  28112. MaterialDefines.prototype.markAsTexturesDirty = function () {
  28113. this._areTexturesDirty = true;
  28114. this._isDirty = true;
  28115. };
  28116. MaterialDefines.prototype.markAsFresnelDirty = function () {
  28117. this._areFresnelDirty = true;
  28118. this._isDirty = true;
  28119. };
  28120. MaterialDefines.prototype.markAsMiscDirty = function () {
  28121. this._areMiscDirty = true;
  28122. this._isDirty = true;
  28123. };
  28124. MaterialDefines.prototype.rebuild = function () {
  28125. if (this._keys) {
  28126. delete this._keys;
  28127. }
  28128. this._keys = [];
  28129. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  28130. var key = _a[_i];
  28131. if (key[0] === "_") {
  28132. continue;
  28133. }
  28134. this._keys.push(key);
  28135. }
  28136. };
  28137. MaterialDefines.prototype.isEqual = function (other) {
  28138. if (this._keys.length !== other._keys.length) {
  28139. return false;
  28140. }
  28141. for (var index = 0; index < this._keys.length; index++) {
  28142. var prop = this._keys[index];
  28143. if (this[prop] !== other[prop]) {
  28144. return false;
  28145. }
  28146. }
  28147. return true;
  28148. };
  28149. MaterialDefines.prototype.cloneTo = function (other) {
  28150. if (this._keys.length !== other._keys.length) {
  28151. other._keys = this._keys.slice(0);
  28152. }
  28153. for (var index = 0; index < this._keys.length; index++) {
  28154. var prop = this._keys[index];
  28155. other[prop] = this[prop];
  28156. }
  28157. };
  28158. MaterialDefines.prototype.reset = function () {
  28159. for (var index = 0; index < this._keys.length; index++) {
  28160. var prop = this._keys[index];
  28161. if (typeof (this[prop]) === "number") {
  28162. this[prop] = 0;
  28163. }
  28164. else {
  28165. this[prop] = false;
  28166. }
  28167. }
  28168. };
  28169. MaterialDefines.prototype.toString = function () {
  28170. var result = "";
  28171. for (var index = 0; index < this._keys.length; index++) {
  28172. var prop = this._keys[index];
  28173. var value = this[prop];
  28174. if (typeof (value) === "number") {
  28175. result += "#define " + prop + " " + this[prop] + "\n";
  28176. }
  28177. else if (value) {
  28178. result += "#define " + prop + "\n";
  28179. }
  28180. }
  28181. return result;
  28182. };
  28183. return MaterialDefines;
  28184. }());
  28185. BABYLON.MaterialDefines = MaterialDefines;
  28186. var Material = /** @class */ (function () {
  28187. function Material(name, scene, doNotAdd) {
  28188. this.checkReadyOnEveryCall = false;
  28189. this.checkReadyOnlyOnce = false;
  28190. this.state = "";
  28191. this.alpha = 1.0;
  28192. this._backFaceCulling = true;
  28193. this.doNotSerialize = false;
  28194. this.storeEffectOnSubMeshes = false;
  28195. /**
  28196. * An event triggered when the material is disposed.
  28197. * @type {BABYLON.Observable}
  28198. */
  28199. this.onDisposeObservable = new BABYLON.Observable();
  28200. /**
  28201. * An event triggered when the material is bound.
  28202. * @type {BABYLON.Observable}
  28203. */
  28204. this.onBindObservable = new BABYLON.Observable();
  28205. /**
  28206. * An event triggered when the material is unbound.
  28207. * @type {BABYLON.Observable}
  28208. */
  28209. this.onUnBindObservable = new BABYLON.Observable();
  28210. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  28211. this._needDepthPrePass = false;
  28212. this.disableDepthWrite = false;
  28213. this.forceDepthWrite = false;
  28214. this.separateCullingPass = false;
  28215. this._fogEnabled = true;
  28216. this.pointSize = 1.0;
  28217. this.zOffset = 0;
  28218. this._wasPreviouslyReady = false;
  28219. this._fillMode = Material.TriangleFillMode;
  28220. this.name = name;
  28221. this.id = name || BABYLON.Tools.RandomId();
  28222. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  28223. if (this._scene.useRightHandedSystem) {
  28224. this.sideOrientation = Material.ClockWiseSideOrientation;
  28225. }
  28226. else {
  28227. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  28228. }
  28229. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  28230. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  28231. if (!doNotAdd) {
  28232. this._scene.materials.push(this);
  28233. }
  28234. }
  28235. Object.defineProperty(Material, "TriangleFillMode", {
  28236. get: function () {
  28237. return Material._TriangleFillMode;
  28238. },
  28239. enumerable: true,
  28240. configurable: true
  28241. });
  28242. Object.defineProperty(Material, "WireFrameFillMode", {
  28243. get: function () {
  28244. return Material._WireFrameFillMode;
  28245. },
  28246. enumerable: true,
  28247. configurable: true
  28248. });
  28249. Object.defineProperty(Material, "PointFillMode", {
  28250. get: function () {
  28251. return Material._PointFillMode;
  28252. },
  28253. enumerable: true,
  28254. configurable: true
  28255. });
  28256. Object.defineProperty(Material, "PointListDrawMode", {
  28257. get: function () {
  28258. return Material._PointListDrawMode;
  28259. },
  28260. enumerable: true,
  28261. configurable: true
  28262. });
  28263. Object.defineProperty(Material, "LineListDrawMode", {
  28264. get: function () {
  28265. return Material._LineListDrawMode;
  28266. },
  28267. enumerable: true,
  28268. configurable: true
  28269. });
  28270. Object.defineProperty(Material, "LineLoopDrawMode", {
  28271. get: function () {
  28272. return Material._LineLoopDrawMode;
  28273. },
  28274. enumerable: true,
  28275. configurable: true
  28276. });
  28277. Object.defineProperty(Material, "LineStripDrawMode", {
  28278. get: function () {
  28279. return Material._LineStripDrawMode;
  28280. },
  28281. enumerable: true,
  28282. configurable: true
  28283. });
  28284. Object.defineProperty(Material, "TriangleStripDrawMode", {
  28285. get: function () {
  28286. return Material._TriangleStripDrawMode;
  28287. },
  28288. enumerable: true,
  28289. configurable: true
  28290. });
  28291. Object.defineProperty(Material, "TriangleFanDrawMode", {
  28292. get: function () {
  28293. return Material._TriangleFanDrawMode;
  28294. },
  28295. enumerable: true,
  28296. configurable: true
  28297. });
  28298. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28299. get: function () {
  28300. return Material._ClockWiseSideOrientation;
  28301. },
  28302. enumerable: true,
  28303. configurable: true
  28304. });
  28305. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28306. get: function () {
  28307. return Material._CounterClockWiseSideOrientation;
  28308. },
  28309. enumerable: true,
  28310. configurable: true
  28311. });
  28312. Object.defineProperty(Material, "TextureDirtyFlag", {
  28313. get: function () {
  28314. return Material._TextureDirtyFlag;
  28315. },
  28316. enumerable: true,
  28317. configurable: true
  28318. });
  28319. Object.defineProperty(Material, "LightDirtyFlag", {
  28320. get: function () {
  28321. return Material._LightDirtyFlag;
  28322. },
  28323. enumerable: true,
  28324. configurable: true
  28325. });
  28326. Object.defineProperty(Material, "FresnelDirtyFlag", {
  28327. get: function () {
  28328. return Material._FresnelDirtyFlag;
  28329. },
  28330. enumerable: true,
  28331. configurable: true
  28332. });
  28333. Object.defineProperty(Material, "AttributesDirtyFlag", {
  28334. get: function () {
  28335. return Material._AttributesDirtyFlag;
  28336. },
  28337. enumerable: true,
  28338. configurable: true
  28339. });
  28340. Object.defineProperty(Material, "MiscDirtyFlag", {
  28341. get: function () {
  28342. return Material._MiscDirtyFlag;
  28343. },
  28344. enumerable: true,
  28345. configurable: true
  28346. });
  28347. Object.defineProperty(Material.prototype, "backFaceCulling", {
  28348. get: function () {
  28349. return this._backFaceCulling;
  28350. },
  28351. set: function (value) {
  28352. if (this._backFaceCulling === value) {
  28353. return;
  28354. }
  28355. this._backFaceCulling = value;
  28356. this.markAsDirty(Material.TextureDirtyFlag);
  28357. },
  28358. enumerable: true,
  28359. configurable: true
  28360. });
  28361. Object.defineProperty(Material.prototype, "onDispose", {
  28362. set: function (callback) {
  28363. if (this._onDisposeObserver) {
  28364. this.onDisposeObservable.remove(this._onDisposeObserver);
  28365. }
  28366. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28367. },
  28368. enumerable: true,
  28369. configurable: true
  28370. });
  28371. Object.defineProperty(Material.prototype, "onBind", {
  28372. set: function (callback) {
  28373. if (this._onBindObserver) {
  28374. this.onBindObservable.remove(this._onBindObserver);
  28375. }
  28376. this._onBindObserver = this.onBindObservable.add(callback);
  28377. },
  28378. enumerable: true,
  28379. configurable: true
  28380. });
  28381. Object.defineProperty(Material.prototype, "alphaMode", {
  28382. get: function () {
  28383. return this._alphaMode;
  28384. },
  28385. set: function (value) {
  28386. if (this._alphaMode === value) {
  28387. return;
  28388. }
  28389. this._alphaMode = value;
  28390. this.markAsDirty(Material.TextureDirtyFlag);
  28391. },
  28392. enumerable: true,
  28393. configurable: true
  28394. });
  28395. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  28396. get: function () {
  28397. return this._needDepthPrePass;
  28398. },
  28399. set: function (value) {
  28400. if (this._needDepthPrePass === value) {
  28401. return;
  28402. }
  28403. this._needDepthPrePass = value;
  28404. if (this._needDepthPrePass) {
  28405. this.checkReadyOnEveryCall = true;
  28406. }
  28407. },
  28408. enumerable: true,
  28409. configurable: true
  28410. });
  28411. Object.defineProperty(Material.prototype, "fogEnabled", {
  28412. get: function () {
  28413. return this._fogEnabled;
  28414. },
  28415. set: function (value) {
  28416. if (this._fogEnabled === value) {
  28417. return;
  28418. }
  28419. this._fogEnabled = value;
  28420. this.markAsDirty(Material.MiscDirtyFlag);
  28421. },
  28422. enumerable: true,
  28423. configurable: true
  28424. });
  28425. Object.defineProperty(Material.prototype, "wireframe", {
  28426. get: function () {
  28427. return this._fillMode === Material.WireFrameFillMode;
  28428. },
  28429. set: function (value) {
  28430. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28431. },
  28432. enumerable: true,
  28433. configurable: true
  28434. });
  28435. Object.defineProperty(Material.prototype, "pointsCloud", {
  28436. get: function () {
  28437. return this._fillMode === Material.PointFillMode;
  28438. },
  28439. set: function (value) {
  28440. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28441. },
  28442. enumerable: true,
  28443. configurable: true
  28444. });
  28445. Object.defineProperty(Material.prototype, "fillMode", {
  28446. get: function () {
  28447. return this._fillMode;
  28448. },
  28449. set: function (value) {
  28450. if (this._fillMode === value) {
  28451. return;
  28452. }
  28453. this._fillMode = value;
  28454. this.markAsDirty(Material.MiscDirtyFlag);
  28455. },
  28456. enumerable: true,
  28457. configurable: true
  28458. });
  28459. /**
  28460. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28461. * subclasses should override adding information pertainent to themselves
  28462. */
  28463. Material.prototype.toString = function (fullDetails) {
  28464. var ret = "Name: " + this.name;
  28465. if (fullDetails) {
  28466. }
  28467. return ret;
  28468. };
  28469. /**
  28470. * Child classes can use it to update shaders
  28471. */
  28472. Material.prototype.getClassName = function () {
  28473. return "Material";
  28474. };
  28475. Object.defineProperty(Material.prototype, "isFrozen", {
  28476. get: function () {
  28477. return this.checkReadyOnlyOnce;
  28478. },
  28479. enumerable: true,
  28480. configurable: true
  28481. });
  28482. Material.prototype.freeze = function () {
  28483. this.checkReadyOnlyOnce = true;
  28484. };
  28485. Material.prototype.unfreeze = function () {
  28486. this.checkReadyOnlyOnce = false;
  28487. };
  28488. Material.prototype.isReady = function (mesh, useInstances) {
  28489. return true;
  28490. };
  28491. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28492. return false;
  28493. };
  28494. Material.prototype.getEffect = function () {
  28495. return this._effect;
  28496. };
  28497. Material.prototype.getScene = function () {
  28498. return this._scene;
  28499. };
  28500. Material.prototype.needAlphaBlending = function () {
  28501. return (this.alpha < 1.0);
  28502. };
  28503. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  28504. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  28505. };
  28506. Material.prototype.needAlphaTesting = function () {
  28507. return false;
  28508. };
  28509. Material.prototype.getAlphaTestTexture = function () {
  28510. return null;
  28511. };
  28512. Material.prototype.markDirty = function () {
  28513. this._wasPreviouslyReady = false;
  28514. };
  28515. Material.prototype._preBind = function (effect, overrideOrientation) {
  28516. if (overrideOrientation === void 0) { overrideOrientation = null; }
  28517. var engine = this._scene.getEngine();
  28518. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  28519. var reverse = orientation === Material.ClockWiseSideOrientation;
  28520. engine.enableEffect(effect ? effect : this._effect);
  28521. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  28522. return reverse;
  28523. };
  28524. Material.prototype.bind = function (world, mesh) {
  28525. };
  28526. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28527. };
  28528. Material.prototype.bindOnlyWorldMatrix = function (world) {
  28529. };
  28530. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  28531. sceneUbo.bindToEffect(effect, "Scene");
  28532. };
  28533. Material.prototype.bindView = function (effect) {
  28534. if (!this._useUBO) {
  28535. effect.setMatrix("view", this.getScene().getViewMatrix());
  28536. }
  28537. else {
  28538. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28539. }
  28540. };
  28541. Material.prototype.bindViewProjection = function (effect) {
  28542. if (!this._useUBO) {
  28543. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28544. }
  28545. else {
  28546. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28547. }
  28548. };
  28549. Material.prototype._afterBind = function (mesh) {
  28550. this._scene._cachedMaterial = this;
  28551. if (mesh) {
  28552. this._scene._cachedVisibility = mesh.visibility;
  28553. }
  28554. else {
  28555. this._scene._cachedVisibility = 1;
  28556. }
  28557. if (mesh) {
  28558. this.onBindObservable.notifyObservers(mesh);
  28559. }
  28560. if (this.disableDepthWrite) {
  28561. var engine = this._scene.getEngine();
  28562. this._cachedDepthWriteState = engine.getDepthWrite();
  28563. engine.setDepthWrite(false);
  28564. }
  28565. };
  28566. Material.prototype.unbind = function () {
  28567. this.onUnBindObservable.notifyObservers(this);
  28568. if (this.disableDepthWrite) {
  28569. var engine = this._scene.getEngine();
  28570. engine.setDepthWrite(this._cachedDepthWriteState);
  28571. }
  28572. };
  28573. Material.prototype.getActiveTextures = function () {
  28574. return [];
  28575. };
  28576. Material.prototype.hasTexture = function (texture) {
  28577. return false;
  28578. };
  28579. Material.prototype.clone = function (name) {
  28580. return null;
  28581. };
  28582. Material.prototype.getBindedMeshes = function () {
  28583. var result = new Array();
  28584. for (var index = 0; index < this._scene.meshes.length; index++) {
  28585. var mesh = this._scene.meshes[index];
  28586. if (mesh.material === this) {
  28587. result.push(mesh);
  28588. }
  28589. }
  28590. return result;
  28591. };
  28592. /**
  28593. * Force shader compilation including textures ready check
  28594. */
  28595. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  28596. var _this = this;
  28597. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  28598. var subMesh = new BABYLON.BaseSubMesh();
  28599. var scene = this.getScene();
  28600. var engine = scene.getEngine();
  28601. var checkReady = function () {
  28602. if (!_this._scene || !_this._scene.getEngine()) {
  28603. return;
  28604. }
  28605. if (subMesh._materialDefines) {
  28606. subMesh._materialDefines._renderId = -1;
  28607. }
  28608. var alphaTestState = engine.getAlphaTesting();
  28609. var clipPlaneState = scene.clipPlane;
  28610. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  28611. if (localOptions.clipPlane) {
  28612. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  28613. }
  28614. if (_this.storeEffectOnSubMeshes) {
  28615. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  28616. if (onCompiled) {
  28617. onCompiled(_this);
  28618. }
  28619. }
  28620. else {
  28621. setTimeout(checkReady, 16);
  28622. }
  28623. }
  28624. else {
  28625. if (_this.isReady(mesh)) {
  28626. if (onCompiled) {
  28627. onCompiled(_this);
  28628. }
  28629. }
  28630. else {
  28631. setTimeout(checkReady, 16);
  28632. }
  28633. }
  28634. engine.setAlphaTesting(alphaTestState);
  28635. if (options && options.clipPlane) {
  28636. scene.clipPlane = clipPlaneState;
  28637. }
  28638. };
  28639. checkReady();
  28640. };
  28641. Material.prototype.markAsDirty = function (flag) {
  28642. if (flag & Material.TextureDirtyFlag) {
  28643. this._markAllSubMeshesAsTexturesDirty();
  28644. }
  28645. if (flag & Material.LightDirtyFlag) {
  28646. this._markAllSubMeshesAsLightsDirty();
  28647. }
  28648. if (flag & Material.FresnelDirtyFlag) {
  28649. this._markAllSubMeshesAsFresnelDirty();
  28650. }
  28651. if (flag & Material.AttributesDirtyFlag) {
  28652. this._markAllSubMeshesAsAttributesDirty();
  28653. }
  28654. if (flag & Material.MiscDirtyFlag) {
  28655. this._markAllSubMeshesAsMiscDirty();
  28656. }
  28657. this.getScene().resetCachedMaterial();
  28658. };
  28659. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  28660. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28661. var mesh = _a[_i];
  28662. if (!mesh.subMeshes) {
  28663. continue;
  28664. }
  28665. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28666. var subMesh = _c[_b];
  28667. if (subMesh.getMaterial() !== this) {
  28668. continue;
  28669. }
  28670. if (!subMesh._materialDefines) {
  28671. continue;
  28672. }
  28673. func(subMesh._materialDefines);
  28674. }
  28675. }
  28676. };
  28677. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28678. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28679. };
  28680. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28681. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28682. };
  28683. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28684. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28685. };
  28686. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28687. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28688. };
  28689. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28690. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28691. };
  28692. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28693. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28694. };
  28695. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28696. // Animations
  28697. this.getScene().stopAnimation(this);
  28698. // Remove from scene
  28699. var index = this._scene.materials.indexOf(this);
  28700. if (index >= 0) {
  28701. this._scene.materials.splice(index, 1);
  28702. }
  28703. // Remove from meshes
  28704. for (index = 0; index < this._scene.meshes.length; index++) {
  28705. var mesh = this._scene.meshes[index];
  28706. if (mesh.material === this) {
  28707. mesh.material = null;
  28708. if (mesh.geometry) {
  28709. var geometry = (mesh.geometry);
  28710. if (this.storeEffectOnSubMeshes) {
  28711. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28712. var subMesh = _a[_i];
  28713. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28714. if (forceDisposeEffect && subMesh._materialEffect) {
  28715. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28716. }
  28717. }
  28718. }
  28719. else {
  28720. geometry._releaseVertexArrayObject(this._effect);
  28721. }
  28722. }
  28723. }
  28724. }
  28725. this._uniformBuffer.dispose();
  28726. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28727. if (forceDisposeEffect && this._effect) {
  28728. if (!this.storeEffectOnSubMeshes) {
  28729. this._scene.getEngine()._releaseEffect(this._effect);
  28730. }
  28731. this._effect = null;
  28732. }
  28733. // Callback
  28734. this.onDisposeObservable.notifyObservers(this);
  28735. this.onDisposeObservable.clear();
  28736. this.onBindObservable.clear();
  28737. this.onUnBindObservable.clear();
  28738. };
  28739. Material.prototype.serialize = function () {
  28740. return BABYLON.SerializationHelper.Serialize(this);
  28741. };
  28742. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28743. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28744. multiMaterial.id = parsedMultiMaterial.id;
  28745. if (BABYLON.Tags) {
  28746. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28747. }
  28748. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28749. var subMatId = parsedMultiMaterial.materials[matIndex];
  28750. if (subMatId) {
  28751. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28752. }
  28753. else {
  28754. multiMaterial.subMaterials.push(null);
  28755. }
  28756. }
  28757. return multiMaterial;
  28758. };
  28759. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28760. if (!parsedMaterial.customType) {
  28761. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28762. }
  28763. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28764. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28765. if (!BABYLON.LegacyPBRMaterial) {
  28766. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28767. return;
  28768. }
  28769. }
  28770. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28771. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28772. ;
  28773. };
  28774. // Triangle views
  28775. Material._TriangleFillMode = 0;
  28776. Material._WireFrameFillMode = 1;
  28777. Material._PointFillMode = 2;
  28778. // Draw modes
  28779. Material._PointListDrawMode = 3;
  28780. Material._LineListDrawMode = 4;
  28781. Material._LineLoopDrawMode = 5;
  28782. Material._LineStripDrawMode = 6;
  28783. Material._TriangleStripDrawMode = 7;
  28784. Material._TriangleFanDrawMode = 8;
  28785. Material._ClockWiseSideOrientation = 0;
  28786. Material._CounterClockWiseSideOrientation = 1;
  28787. Material._TextureDirtyFlag = 1;
  28788. Material._LightDirtyFlag = 2;
  28789. Material._FresnelDirtyFlag = 4;
  28790. Material._AttributesDirtyFlag = 8;
  28791. Material._MiscDirtyFlag = 16;
  28792. __decorate([
  28793. BABYLON.serialize()
  28794. ], Material.prototype, "id", void 0);
  28795. __decorate([
  28796. BABYLON.serialize()
  28797. ], Material.prototype, "name", void 0);
  28798. __decorate([
  28799. BABYLON.serialize()
  28800. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28801. __decorate([
  28802. BABYLON.serialize()
  28803. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28804. __decorate([
  28805. BABYLON.serialize()
  28806. ], Material.prototype, "state", void 0);
  28807. __decorate([
  28808. BABYLON.serialize()
  28809. ], Material.prototype, "alpha", void 0);
  28810. __decorate([
  28811. BABYLON.serialize("backFaceCulling")
  28812. ], Material.prototype, "_backFaceCulling", void 0);
  28813. __decorate([
  28814. BABYLON.serialize()
  28815. ], Material.prototype, "sideOrientation", void 0);
  28816. __decorate([
  28817. BABYLON.serialize("alphaMode")
  28818. ], Material.prototype, "_alphaMode", void 0);
  28819. __decorate([
  28820. BABYLON.serialize()
  28821. ], Material.prototype, "_needDepthPrePass", void 0);
  28822. __decorate([
  28823. BABYLON.serialize()
  28824. ], Material.prototype, "disableDepthWrite", void 0);
  28825. __decorate([
  28826. BABYLON.serialize()
  28827. ], Material.prototype, "forceDepthWrite", void 0);
  28828. __decorate([
  28829. BABYLON.serialize()
  28830. ], Material.prototype, "separateCullingPass", void 0);
  28831. __decorate([
  28832. BABYLON.serialize("fogEnabled")
  28833. ], Material.prototype, "_fogEnabled", void 0);
  28834. __decorate([
  28835. BABYLON.serialize()
  28836. ], Material.prototype, "pointSize", void 0);
  28837. __decorate([
  28838. BABYLON.serialize()
  28839. ], Material.prototype, "zOffset", void 0);
  28840. __decorate([
  28841. BABYLON.serialize()
  28842. ], Material.prototype, "wireframe", null);
  28843. __decorate([
  28844. BABYLON.serialize()
  28845. ], Material.prototype, "pointsCloud", null);
  28846. __decorate([
  28847. BABYLON.serialize()
  28848. ], Material.prototype, "fillMode", null);
  28849. return Material;
  28850. }());
  28851. BABYLON.Material = Material;
  28852. })(BABYLON || (BABYLON = {}));
  28853. //# sourceMappingURL=babylon.material.js.map
  28854. var BABYLON;
  28855. (function (BABYLON) {
  28856. var UniformBuffer = /** @class */ (function () {
  28857. /**
  28858. * Uniform buffer objects.
  28859. *
  28860. * Handles blocks of uniform on the GPU.
  28861. *
  28862. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28863. *
  28864. * For more information, please refer to :
  28865. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28866. */
  28867. function UniformBuffer(engine, data, dynamic) {
  28868. this._engine = engine;
  28869. this._noUBO = !engine.supportsUniformBuffers;
  28870. this._dynamic = dynamic;
  28871. this._data = data || [];
  28872. this._uniformLocations = {};
  28873. this._uniformSizes = {};
  28874. this._uniformLocationPointer = 0;
  28875. this._needSync = false;
  28876. if (this._noUBO) {
  28877. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28878. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28879. this.updateFloat = this._updateFloatForEffect;
  28880. this.updateFloat2 = this._updateFloat2ForEffect;
  28881. this.updateFloat3 = this._updateFloat3ForEffect;
  28882. this.updateFloat4 = this._updateFloat4ForEffect;
  28883. this.updateMatrix = this._updateMatrixForEffect;
  28884. this.updateVector3 = this._updateVector3ForEffect;
  28885. this.updateVector4 = this._updateVector4ForEffect;
  28886. this.updateColor3 = this._updateColor3ForEffect;
  28887. this.updateColor4 = this._updateColor4ForEffect;
  28888. }
  28889. else {
  28890. this._engine._uniformBuffers.push(this);
  28891. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28892. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28893. this.updateFloat = this._updateFloatForUniform;
  28894. this.updateFloat2 = this._updateFloat2ForUniform;
  28895. this.updateFloat3 = this._updateFloat3ForUniform;
  28896. this.updateFloat4 = this._updateFloat4ForUniform;
  28897. this.updateMatrix = this._updateMatrixForUniform;
  28898. this.updateVector3 = this._updateVector3ForUniform;
  28899. this.updateVector4 = this._updateVector4ForUniform;
  28900. this.updateColor3 = this._updateColor3ForUniform;
  28901. this.updateColor4 = this._updateColor4ForUniform;
  28902. }
  28903. }
  28904. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28905. // Properties
  28906. /**
  28907. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28908. * or just falling back on setUniformXXX calls.
  28909. */
  28910. get: function () {
  28911. return !this._noUBO;
  28912. },
  28913. enumerable: true,
  28914. configurable: true
  28915. });
  28916. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28917. /**
  28918. * Indicates if the WebGL underlying uniform buffer is in sync
  28919. * with the javascript cache data.
  28920. */
  28921. get: function () {
  28922. return !this._needSync;
  28923. },
  28924. enumerable: true,
  28925. configurable: true
  28926. });
  28927. /**
  28928. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28929. * Also, a dynamic UniformBuffer will disable cache verification and always
  28930. * update the underlying WebGL uniform buffer to the GPU.
  28931. */
  28932. UniformBuffer.prototype.isDynamic = function () {
  28933. return this._dynamic !== undefined;
  28934. };
  28935. /**
  28936. * The data cache on JS side.
  28937. */
  28938. UniformBuffer.prototype.getData = function () {
  28939. return this._bufferData;
  28940. };
  28941. /**
  28942. * The underlying WebGL Uniform buffer.
  28943. */
  28944. UniformBuffer.prototype.getBuffer = function () {
  28945. return this._buffer;
  28946. };
  28947. /**
  28948. * std140 layout specifies how to align data within an UBO structure.
  28949. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28950. * for specs.
  28951. */
  28952. UniformBuffer.prototype._fillAlignment = function (size) {
  28953. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28954. // and 4x4 matrices
  28955. // TODO : change if other types are used
  28956. var alignment;
  28957. if (size <= 2) {
  28958. alignment = size;
  28959. }
  28960. else {
  28961. alignment = 4;
  28962. }
  28963. if ((this._uniformLocationPointer % alignment) !== 0) {
  28964. var oldPointer = this._uniformLocationPointer;
  28965. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28966. var diff = this._uniformLocationPointer - oldPointer;
  28967. for (var i = 0; i < diff; i++) {
  28968. this._data.push(0);
  28969. }
  28970. }
  28971. };
  28972. /**
  28973. * Adds an uniform in the buffer.
  28974. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28975. * for the layout to be correct !
  28976. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28977. * @param {number|number[]} size Data size, or data directly.
  28978. */
  28979. UniformBuffer.prototype.addUniform = function (name, size) {
  28980. if (this._noUBO) {
  28981. return;
  28982. }
  28983. if (this._uniformLocations[name] !== undefined) {
  28984. // Already existing uniform
  28985. return;
  28986. }
  28987. // This function must be called in the order of the shader layout !
  28988. // size can be the size of the uniform, or data directly
  28989. var data;
  28990. if (size instanceof Array) {
  28991. data = size;
  28992. size = data.length;
  28993. }
  28994. else {
  28995. size = size;
  28996. data = [];
  28997. // Fill with zeros
  28998. for (var i = 0; i < size; i++) {
  28999. data.push(0);
  29000. }
  29001. }
  29002. this._fillAlignment(size);
  29003. this._uniformSizes[name] = size;
  29004. this._uniformLocations[name] = this._uniformLocationPointer;
  29005. this._uniformLocationPointer += size;
  29006. for (var i = 0; i < size; i++) {
  29007. this._data.push(data[i]);
  29008. }
  29009. this._needSync = true;
  29010. };
  29011. /**
  29012. * Wrapper for addUniform.
  29013. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29014. * @param {Matrix} mat A 4x4 matrix.
  29015. */
  29016. UniformBuffer.prototype.addMatrix = function (name, mat) {
  29017. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  29018. };
  29019. /**
  29020. * Wrapper for addUniform.
  29021. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29022. * @param {number} x
  29023. * @param {number} y
  29024. */
  29025. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  29026. var temp = [x, y];
  29027. this.addUniform(name, temp);
  29028. };
  29029. /**
  29030. * Wrapper for addUniform.
  29031. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29032. * @param {number} x
  29033. * @param {number} y
  29034. * @param {number} z
  29035. */
  29036. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  29037. var temp = [x, y, z];
  29038. this.addUniform(name, temp);
  29039. };
  29040. /**
  29041. * Wrapper for addUniform.
  29042. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29043. * @param {Color3} color
  29044. */
  29045. UniformBuffer.prototype.addColor3 = function (name, color) {
  29046. var temp = new Array();
  29047. color.toArray(temp);
  29048. this.addUniform(name, temp);
  29049. };
  29050. /**
  29051. * Wrapper for addUniform.
  29052. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29053. * @param {Color3} color
  29054. * @param {number} alpha
  29055. */
  29056. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  29057. var temp = new Array();
  29058. color.toArray(temp);
  29059. temp.push(alpha);
  29060. this.addUniform(name, temp);
  29061. };
  29062. /**
  29063. * Wrapper for addUniform.
  29064. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29065. * @param {Vector3} vector
  29066. */
  29067. UniformBuffer.prototype.addVector3 = function (name, vector) {
  29068. var temp = new Array();
  29069. vector.toArray(temp);
  29070. this.addUniform(name, temp);
  29071. };
  29072. /**
  29073. * Wrapper for addUniform.
  29074. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29075. */
  29076. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  29077. this.addUniform(name, 12);
  29078. };
  29079. /**
  29080. * Wrapper for addUniform.
  29081. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29082. */
  29083. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  29084. this.addUniform(name, 8);
  29085. };
  29086. /**
  29087. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  29088. */
  29089. UniformBuffer.prototype.create = function () {
  29090. if (this._noUBO) {
  29091. return;
  29092. }
  29093. if (this._buffer) {
  29094. return; // nothing to do
  29095. }
  29096. // See spec, alignment must be filled as a vec4
  29097. this._fillAlignment(4);
  29098. this._bufferData = new Float32Array(this._data);
  29099. this._rebuild();
  29100. this._needSync = true;
  29101. };
  29102. UniformBuffer.prototype._rebuild = function () {
  29103. if (this._noUBO) {
  29104. return;
  29105. }
  29106. if (this._dynamic) {
  29107. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  29108. }
  29109. else {
  29110. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  29111. }
  29112. };
  29113. /**
  29114. * Updates the WebGL Uniform Buffer on the GPU.
  29115. * If the `dynamic` flag is set to true, no cache comparison is done.
  29116. * Otherwise, the buffer will be updated only if the cache differs.
  29117. */
  29118. UniformBuffer.prototype.update = function () {
  29119. if (!this._buffer) {
  29120. this.create();
  29121. return;
  29122. }
  29123. if (!this._dynamic && !this._needSync) {
  29124. return;
  29125. }
  29126. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  29127. this._needSync = false;
  29128. };
  29129. /**
  29130. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  29131. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29132. * @param {number[]|Float32Array} data Flattened data
  29133. * @param {number} size Size of the data.
  29134. */
  29135. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  29136. var location = this._uniformLocations[uniformName];
  29137. if (location === undefined) {
  29138. if (this._buffer) {
  29139. // Cannot add an uniform if the buffer is already created
  29140. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  29141. return;
  29142. }
  29143. this.addUniform(uniformName, size);
  29144. location = this._uniformLocations[uniformName];
  29145. }
  29146. if (!this._buffer) {
  29147. this.create();
  29148. }
  29149. if (!this._dynamic) {
  29150. // Cache for static uniform buffers
  29151. var changed = false;
  29152. for (var i = 0; i < size; i++) {
  29153. if (this._bufferData[location + i] !== data[i]) {
  29154. changed = true;
  29155. this._bufferData[location + i] = data[i];
  29156. }
  29157. }
  29158. this._needSync = this._needSync || changed;
  29159. }
  29160. else {
  29161. // No cache for dynamic
  29162. for (var i = 0; i < size; i++) {
  29163. this._bufferData[location + i] = data[i];
  29164. }
  29165. }
  29166. };
  29167. // Update methods
  29168. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  29169. // To match std140, matrix must be realigned
  29170. for (var i = 0; i < 3; i++) {
  29171. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  29172. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  29173. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  29174. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29175. }
  29176. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  29177. };
  29178. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  29179. this._currentEffect.setMatrix3x3(name, matrix);
  29180. };
  29181. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  29182. this._currentEffect.setMatrix2x2(name, matrix);
  29183. };
  29184. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  29185. // To match std140, matrix must be realigned
  29186. for (var i = 0; i < 2; i++) {
  29187. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  29188. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  29189. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  29190. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29191. }
  29192. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  29193. };
  29194. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  29195. this._currentEffect.setFloat(name, x);
  29196. };
  29197. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  29198. UniformBuffer._tempBuffer[0] = x;
  29199. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  29200. };
  29201. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  29202. if (suffix === void 0) { suffix = ""; }
  29203. this._currentEffect.setFloat2(name + suffix, x, y);
  29204. };
  29205. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  29206. if (suffix === void 0) { suffix = ""; }
  29207. UniformBuffer._tempBuffer[0] = x;
  29208. UniformBuffer._tempBuffer[1] = y;
  29209. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  29210. };
  29211. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  29212. if (suffix === void 0) { suffix = ""; }
  29213. this._currentEffect.setFloat3(name + suffix, x, y, z);
  29214. };
  29215. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  29216. if (suffix === void 0) { suffix = ""; }
  29217. UniformBuffer._tempBuffer[0] = x;
  29218. UniformBuffer._tempBuffer[1] = y;
  29219. UniformBuffer._tempBuffer[2] = z;
  29220. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29221. };
  29222. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  29223. if (suffix === void 0) { suffix = ""; }
  29224. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  29225. };
  29226. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  29227. if (suffix === void 0) { suffix = ""; }
  29228. UniformBuffer._tempBuffer[0] = x;
  29229. UniformBuffer._tempBuffer[1] = y;
  29230. UniformBuffer._tempBuffer[2] = z;
  29231. UniformBuffer._tempBuffer[3] = w;
  29232. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29233. };
  29234. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  29235. this._currentEffect.setMatrix(name, mat);
  29236. };
  29237. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  29238. this.updateUniform(name, mat.toArray(), 16);
  29239. };
  29240. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  29241. this._currentEffect.setVector3(name, vector);
  29242. };
  29243. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  29244. vector.toArray(UniformBuffer._tempBuffer);
  29245. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29246. };
  29247. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  29248. this._currentEffect.setVector4(name, vector);
  29249. };
  29250. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  29251. vector.toArray(UniformBuffer._tempBuffer);
  29252. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29253. };
  29254. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  29255. if (suffix === void 0) { suffix = ""; }
  29256. this._currentEffect.setColor3(name + suffix, color);
  29257. };
  29258. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  29259. if (suffix === void 0) { suffix = ""; }
  29260. color.toArray(UniformBuffer._tempBuffer);
  29261. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29262. };
  29263. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  29264. if (suffix === void 0) { suffix = ""; }
  29265. this._currentEffect.setColor4(name + suffix, color, alpha);
  29266. };
  29267. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  29268. if (suffix === void 0) { suffix = ""; }
  29269. color.toArray(UniformBuffer._tempBuffer);
  29270. UniformBuffer._tempBuffer[3] = alpha;
  29271. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29272. };
  29273. /**
  29274. * Sets a sampler uniform on the effect.
  29275. * @param {string} name Name of the sampler.
  29276. * @param {Texture} texture
  29277. */
  29278. UniformBuffer.prototype.setTexture = function (name, texture) {
  29279. this._currentEffect.setTexture(name, texture);
  29280. };
  29281. /**
  29282. * Directly updates the value of the uniform in the cache AND on the GPU.
  29283. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29284. * @param {number[]|Float32Array} data Flattened data
  29285. */
  29286. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  29287. this.updateUniform(uniformName, data, data.length);
  29288. this.update();
  29289. };
  29290. /**
  29291. * Binds this uniform buffer to an effect.
  29292. * @param {Effect} effect
  29293. * @param {string} name Name of the uniform block in the shader.
  29294. */
  29295. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  29296. this._currentEffect = effect;
  29297. if (this._noUBO || !this._buffer) {
  29298. return;
  29299. }
  29300. effect.bindUniformBuffer(this._buffer, name);
  29301. };
  29302. /**
  29303. * Disposes the uniform buffer.
  29304. */
  29305. UniformBuffer.prototype.dispose = function () {
  29306. if (this._noUBO) {
  29307. return;
  29308. }
  29309. var index = this._engine._uniformBuffers.indexOf(this);
  29310. if (index !== -1) {
  29311. this._engine._uniformBuffers.splice(index, 1);
  29312. }
  29313. if (!this._buffer) {
  29314. return;
  29315. }
  29316. if (this._engine._releaseBuffer(this._buffer)) {
  29317. this._buffer = null;
  29318. }
  29319. };
  29320. // Pool for avoiding memory leaks
  29321. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  29322. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  29323. return UniformBuffer;
  29324. }());
  29325. BABYLON.UniformBuffer = UniformBuffer;
  29326. })(BABYLON || (BABYLON = {}));
  29327. //# sourceMappingURL=babylon.uniformBuffer.js.map
  29328. var BABYLON;
  29329. (function (BABYLON) {
  29330. var VertexData = /** @class */ (function () {
  29331. function VertexData() {
  29332. }
  29333. VertexData.prototype.set = function (data, kind) {
  29334. switch (kind) {
  29335. case BABYLON.VertexBuffer.PositionKind:
  29336. this.positions = data;
  29337. break;
  29338. case BABYLON.VertexBuffer.NormalKind:
  29339. this.normals = data;
  29340. break;
  29341. case BABYLON.VertexBuffer.TangentKind:
  29342. this.tangents = data;
  29343. break;
  29344. case BABYLON.VertexBuffer.UVKind:
  29345. this.uvs = data;
  29346. break;
  29347. case BABYLON.VertexBuffer.UV2Kind:
  29348. this.uvs2 = data;
  29349. break;
  29350. case BABYLON.VertexBuffer.UV3Kind:
  29351. this.uvs3 = data;
  29352. break;
  29353. case BABYLON.VertexBuffer.UV4Kind:
  29354. this.uvs4 = data;
  29355. break;
  29356. case BABYLON.VertexBuffer.UV5Kind:
  29357. this.uvs5 = data;
  29358. break;
  29359. case BABYLON.VertexBuffer.UV6Kind:
  29360. this.uvs6 = data;
  29361. break;
  29362. case BABYLON.VertexBuffer.ColorKind:
  29363. this.colors = data;
  29364. break;
  29365. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29366. this.matricesIndices = data;
  29367. break;
  29368. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29369. this.matricesWeights = data;
  29370. break;
  29371. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29372. this.matricesIndicesExtra = data;
  29373. break;
  29374. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29375. this.matricesWeightsExtra = data;
  29376. break;
  29377. }
  29378. };
  29379. /**
  29380. * Associates the vertexData to the passed Mesh.
  29381. * Sets it as updatable or not (default `false`).
  29382. * Returns the VertexData.
  29383. */
  29384. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29385. this._applyTo(mesh, updatable);
  29386. return this;
  29387. };
  29388. /**
  29389. * Associates the vertexData to the passed Geometry.
  29390. * Sets it as updatable or not (default `false`).
  29391. * Returns the VertexData.
  29392. */
  29393. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29394. this._applyTo(geometry, updatable);
  29395. return this;
  29396. };
  29397. /**
  29398. * Updates the associated mesh.
  29399. * Returns the VertexData.
  29400. */
  29401. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29402. this._update(mesh);
  29403. return this;
  29404. };
  29405. /**
  29406. * Updates the associated geometry.
  29407. * Returns the VertexData.
  29408. */
  29409. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29410. this._update(geometry);
  29411. return this;
  29412. };
  29413. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29414. if (updatable === void 0) { updatable = false; }
  29415. if (this.positions) {
  29416. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29417. }
  29418. if (this.normals) {
  29419. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29420. }
  29421. if (this.tangents) {
  29422. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  29423. }
  29424. if (this.uvs) {
  29425. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29426. }
  29427. if (this.uvs2) {
  29428. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29429. }
  29430. if (this.uvs3) {
  29431. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29432. }
  29433. if (this.uvs4) {
  29434. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29435. }
  29436. if (this.uvs5) {
  29437. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29438. }
  29439. if (this.uvs6) {
  29440. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29441. }
  29442. if (this.colors) {
  29443. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29444. }
  29445. if (this.matricesIndices) {
  29446. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29447. }
  29448. if (this.matricesWeights) {
  29449. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29450. }
  29451. if (this.matricesIndicesExtra) {
  29452. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29453. }
  29454. if (this.matricesWeightsExtra) {
  29455. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29456. }
  29457. if (this.indices) {
  29458. meshOrGeometry.setIndices(this.indices, null, updatable);
  29459. }
  29460. return this;
  29461. };
  29462. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29463. if (this.positions) {
  29464. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29465. }
  29466. if (this.normals) {
  29467. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29468. }
  29469. if (this.tangents) {
  29470. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  29471. }
  29472. if (this.uvs) {
  29473. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29474. }
  29475. if (this.uvs2) {
  29476. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29477. }
  29478. if (this.uvs3) {
  29479. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29480. }
  29481. if (this.uvs4) {
  29482. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29483. }
  29484. if (this.uvs5) {
  29485. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29486. }
  29487. if (this.uvs6) {
  29488. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29489. }
  29490. if (this.colors) {
  29491. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29492. }
  29493. if (this.matricesIndices) {
  29494. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29495. }
  29496. if (this.matricesWeights) {
  29497. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29498. }
  29499. if (this.matricesIndicesExtra) {
  29500. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29501. }
  29502. if (this.matricesWeightsExtra) {
  29503. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29504. }
  29505. if (this.indices) {
  29506. meshOrGeometry.setIndices(this.indices, null);
  29507. }
  29508. return this;
  29509. };
  29510. /**
  29511. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  29512. * Returns the VertexData.
  29513. */
  29514. VertexData.prototype.transform = function (matrix) {
  29515. var transformed = BABYLON.Vector3.Zero();
  29516. var index;
  29517. if (this.positions) {
  29518. var position = BABYLON.Vector3.Zero();
  29519. for (index = 0; index < this.positions.length; index += 3) {
  29520. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29521. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29522. this.positions[index] = transformed.x;
  29523. this.positions[index + 1] = transformed.y;
  29524. this.positions[index + 2] = transformed.z;
  29525. }
  29526. }
  29527. if (this.normals) {
  29528. var normal = BABYLON.Vector3.Zero();
  29529. for (index = 0; index < this.normals.length; index += 3) {
  29530. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29531. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29532. this.normals[index] = transformed.x;
  29533. this.normals[index + 1] = transformed.y;
  29534. this.normals[index + 2] = transformed.z;
  29535. }
  29536. }
  29537. if (this.tangents) {
  29538. var tangent = BABYLON.Vector4.Zero();
  29539. var tangentTransformed = BABYLON.Vector4.Zero();
  29540. for (index = 0; index < this.tangents.length; index += 4) {
  29541. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  29542. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  29543. this.tangents[index] = tangentTransformed.x;
  29544. this.tangents[index + 1] = tangentTransformed.y;
  29545. this.tangents[index + 2] = tangentTransformed.z;
  29546. this.tangents[index + 3] = tangentTransformed.w;
  29547. }
  29548. }
  29549. return this;
  29550. };
  29551. /**
  29552. * Merges the passed VertexData into the current one.
  29553. * Returns the modified VertexData.
  29554. */
  29555. VertexData.prototype.merge = function (other, options) {
  29556. options = options || {};
  29557. if (other.indices) {
  29558. if (!this.indices) {
  29559. this.indices = [];
  29560. }
  29561. var offset = this.positions ? this.positions.length / 3 : 0;
  29562. for (var index = 0; index < other.indices.length; index++) {
  29563. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  29564. this.indices.push(other.indices[index] + offset);
  29565. }
  29566. }
  29567. this.positions = this._mergeElement(this.positions, other.positions);
  29568. if (!this.positions) {
  29569. return this;
  29570. }
  29571. var count = this.positions.length / 3;
  29572. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  29573. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  29574. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  29575. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  29576. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  29577. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  29578. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  29579. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  29580. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  29581. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  29582. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  29583. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  29584. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  29585. return this;
  29586. };
  29587. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  29588. if (length === void 0) { length = 0; }
  29589. if (defaultValue === void 0) { defaultValue = 0; }
  29590. if (!other && !source) {
  29591. return null;
  29592. }
  29593. if (!other) {
  29594. var padding = new Float32Array(source.length);
  29595. padding.fill(defaultValue);
  29596. return this._mergeElement(source, padding, length);
  29597. }
  29598. if (!source) {
  29599. if (length === 0 || length === other.length) {
  29600. return other;
  29601. }
  29602. var padding = new Float32Array(length - other.length);
  29603. padding.fill(defaultValue);
  29604. return this._mergeElement(padding, other, length);
  29605. }
  29606. var len = other.length + source.length;
  29607. var isSrcTypedArray = source instanceof Float32Array;
  29608. var isOthTypedArray = other instanceof Float32Array;
  29609. // use non-loop method when the source is Float32Array
  29610. if (isSrcTypedArray) {
  29611. var ret32 = new Float32Array(len);
  29612. ret32.set(source);
  29613. ret32.set(other, source.length);
  29614. return ret32;
  29615. // source is number[], when other is also use concat
  29616. }
  29617. else if (!isOthTypedArray) {
  29618. return source.concat(other);
  29619. // source is a number[], but other is a Float32Array, loop required
  29620. }
  29621. else {
  29622. var ret = source.slice(0); // copy source to a separate array
  29623. for (var i = 0, len = other.length; i < len; i++) {
  29624. ret.push(other[i]);
  29625. }
  29626. return ret;
  29627. }
  29628. };
  29629. /**
  29630. * Serializes the VertexData.
  29631. * Returns a serialized object.
  29632. */
  29633. VertexData.prototype.serialize = function () {
  29634. var serializationObject = this.serialize();
  29635. if (this.positions) {
  29636. serializationObject.positions = this.positions;
  29637. }
  29638. if (this.normals) {
  29639. serializationObject.normals = this.normals;
  29640. }
  29641. if (this.tangents) {
  29642. serializationObject.tangents = this.tangents;
  29643. }
  29644. if (this.uvs) {
  29645. serializationObject.uvs = this.uvs;
  29646. }
  29647. if (this.uvs2) {
  29648. serializationObject.uvs2 = this.uvs2;
  29649. }
  29650. if (this.uvs3) {
  29651. serializationObject.uvs3 = this.uvs3;
  29652. }
  29653. if (this.uvs4) {
  29654. serializationObject.uvs4 = this.uvs4;
  29655. }
  29656. if (this.uvs5) {
  29657. serializationObject.uvs5 = this.uvs5;
  29658. }
  29659. if (this.uvs6) {
  29660. serializationObject.uvs6 = this.uvs6;
  29661. }
  29662. if (this.colors) {
  29663. serializationObject.colors = this.colors;
  29664. }
  29665. if (this.matricesIndices) {
  29666. serializationObject.matricesIndices = this.matricesIndices;
  29667. serializationObject.matricesIndices._isExpanded = true;
  29668. }
  29669. if (this.matricesWeights) {
  29670. serializationObject.matricesWeights = this.matricesWeights;
  29671. }
  29672. if (this.matricesIndicesExtra) {
  29673. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29674. serializationObject.matricesIndicesExtra._isExpanded = true;
  29675. }
  29676. if (this.matricesWeightsExtra) {
  29677. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29678. }
  29679. serializationObject.indices = this.indices;
  29680. return serializationObject;
  29681. };
  29682. // Statics
  29683. /**
  29684. * Returns the object VertexData associated to the passed mesh.
  29685. */
  29686. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29687. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29688. };
  29689. /**
  29690. * Returns the object VertexData associated to the passed geometry.
  29691. */
  29692. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29693. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29694. };
  29695. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29696. var result = new VertexData();
  29697. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29698. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29699. }
  29700. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29701. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29702. }
  29703. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29704. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29705. }
  29706. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29707. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29708. }
  29709. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29710. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29711. }
  29712. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29713. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29714. }
  29715. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29716. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29717. }
  29718. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29719. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29720. }
  29721. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29722. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29723. }
  29724. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29725. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29726. }
  29727. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29728. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29729. }
  29730. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29731. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29732. }
  29733. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29734. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29735. }
  29736. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29737. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29738. }
  29739. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29740. return result;
  29741. };
  29742. /**
  29743. * Creates the vertexData of the Ribbon.
  29744. */
  29745. VertexData.CreateRibbon = function (options) {
  29746. var pathArray = options.pathArray;
  29747. var closeArray = options.closeArray || false;
  29748. var closePath = options.closePath || false;
  29749. var invertUV = options.invertUV || false;
  29750. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29751. var offset = options.offset || defaultOffset;
  29752. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29753. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29754. var customUV = options.uvs;
  29755. var customColors = options.colors;
  29756. var positions = [];
  29757. var indices = [];
  29758. var normals = [];
  29759. var uvs = [];
  29760. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29761. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29762. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29763. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29764. var minlg; // minimal length among all paths from pathArray
  29765. var lg = []; // array of path lengths : nb of vertex per path
  29766. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29767. var p; // path iterator
  29768. var i; // point iterator
  29769. var j; // point iterator
  29770. // if single path in pathArray
  29771. if (pathArray.length < 2) {
  29772. var ar1 = [];
  29773. var ar2 = [];
  29774. for (i = 0; i < pathArray[0].length - offset; i++) {
  29775. ar1.push(pathArray[0][i]);
  29776. ar2.push(pathArray[0][i + offset]);
  29777. }
  29778. pathArray = [ar1, ar2];
  29779. }
  29780. // positions and horizontal distances (u)
  29781. var idc = 0;
  29782. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29783. var path;
  29784. var l;
  29785. minlg = pathArray[0].length;
  29786. var vectlg;
  29787. var dist;
  29788. for (p = 0; p < pathArray.length; p++) {
  29789. uTotalDistance[p] = 0;
  29790. us[p] = [0];
  29791. path = pathArray[p];
  29792. l = path.length;
  29793. minlg = (minlg < l) ? minlg : l;
  29794. j = 0;
  29795. while (j < l) {
  29796. positions.push(path[j].x, path[j].y, path[j].z);
  29797. if (j > 0) {
  29798. vectlg = path[j].subtract(path[j - 1]).length();
  29799. dist = vectlg + uTotalDistance[p];
  29800. us[p].push(dist);
  29801. uTotalDistance[p] = dist;
  29802. }
  29803. j++;
  29804. }
  29805. if (closePath) {
  29806. j--;
  29807. positions.push(path[0].x, path[0].y, path[0].z);
  29808. vectlg = path[j].subtract(path[0]).length();
  29809. dist = vectlg + uTotalDistance[p];
  29810. us[p].push(dist);
  29811. uTotalDistance[p] = dist;
  29812. }
  29813. lg[p] = l + closePathCorr;
  29814. idx[p] = idc;
  29815. idc += (l + closePathCorr);
  29816. }
  29817. // vertical distances (v)
  29818. var path1;
  29819. var path2;
  29820. var vertex1 = null;
  29821. var vertex2 = null;
  29822. for (i = 0; i < minlg + closePathCorr; i++) {
  29823. vTotalDistance[i] = 0;
  29824. vs[i] = [0];
  29825. for (p = 0; p < pathArray.length - 1; p++) {
  29826. path1 = pathArray[p];
  29827. path2 = pathArray[p + 1];
  29828. if (i === minlg) {
  29829. vertex1 = path1[0];
  29830. vertex2 = path2[0];
  29831. }
  29832. else {
  29833. vertex1 = path1[i];
  29834. vertex2 = path2[i];
  29835. }
  29836. vectlg = vertex2.subtract(vertex1).length();
  29837. dist = vectlg + vTotalDistance[i];
  29838. vs[i].push(dist);
  29839. vTotalDistance[i] = dist;
  29840. }
  29841. if (closeArray && vertex2 && vertex1) {
  29842. path1 = pathArray[p];
  29843. path2 = pathArray[0];
  29844. if (i === minlg) {
  29845. vertex2 = path2[0];
  29846. }
  29847. vectlg = vertex2.subtract(vertex1).length();
  29848. dist = vectlg + vTotalDistance[i];
  29849. vTotalDistance[i] = dist;
  29850. }
  29851. }
  29852. // uvs
  29853. var u;
  29854. var v;
  29855. if (customUV) {
  29856. for (p = 0; p < customUV.length; p++) {
  29857. uvs.push(customUV[p].x, customUV[p].y);
  29858. }
  29859. }
  29860. else {
  29861. for (p = 0; p < pathArray.length; p++) {
  29862. for (i = 0; i < minlg + closePathCorr; i++) {
  29863. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29864. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29865. if (invertUV) {
  29866. uvs.push(v, u);
  29867. }
  29868. else {
  29869. uvs.push(u, v);
  29870. }
  29871. }
  29872. }
  29873. }
  29874. // indices
  29875. p = 0; // path index
  29876. var pi = 0; // positions array index
  29877. var l1 = lg[p] - 1; // path1 length
  29878. var l2 = lg[p + 1] - 1; // path2 length
  29879. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29880. var shft = idx[1] - idx[0]; // shift
  29881. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29882. while (pi <= min && p < path1nb) {
  29883. // 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
  29884. indices.push(pi, pi + shft, pi + 1);
  29885. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29886. pi += 1;
  29887. if (pi === min) {
  29888. p++;
  29889. if (p === lg.length - 1) {
  29890. shft = idx[0] - idx[p];
  29891. l1 = lg[p] - 1;
  29892. l2 = lg[0] - 1;
  29893. }
  29894. else {
  29895. shft = idx[p + 1] - idx[p];
  29896. l1 = lg[p] - 1;
  29897. l2 = lg[p + 1] - 1;
  29898. }
  29899. pi = idx[p];
  29900. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29901. }
  29902. }
  29903. // normals
  29904. VertexData.ComputeNormals(positions, indices, normals);
  29905. if (closePath) {
  29906. var indexFirst = 0;
  29907. var indexLast = 0;
  29908. for (p = 0; p < pathArray.length; p++) {
  29909. indexFirst = idx[p] * 3;
  29910. if (p + 1 < pathArray.length) {
  29911. indexLast = (idx[p + 1] - 1) * 3;
  29912. }
  29913. else {
  29914. indexLast = normals.length - 3;
  29915. }
  29916. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29917. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29918. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29919. normals[indexLast] = normals[indexFirst];
  29920. normals[indexLast + 1] = normals[indexFirst + 1];
  29921. normals[indexLast + 2] = normals[indexFirst + 2];
  29922. }
  29923. }
  29924. // sides
  29925. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29926. // Colors
  29927. var colors = null;
  29928. if (customColors) {
  29929. colors = new Float32Array(customColors.length * 4);
  29930. for (var c = 0; c < customColors.length; c++) {
  29931. colors[c * 4] = customColors[c].r;
  29932. colors[c * 4 + 1] = customColors[c].g;
  29933. colors[c * 4 + 2] = customColors[c].b;
  29934. colors[c * 4 + 3] = customColors[c].a;
  29935. }
  29936. }
  29937. // Result
  29938. var vertexData = new VertexData();
  29939. var positions32 = new Float32Array(positions);
  29940. var normals32 = new Float32Array(normals);
  29941. var uvs32 = new Float32Array(uvs);
  29942. vertexData.indices = indices;
  29943. vertexData.positions = positions32;
  29944. vertexData.normals = normals32;
  29945. vertexData.uvs = uvs32;
  29946. if (colors) {
  29947. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29948. }
  29949. if (closePath) {
  29950. vertexData._idx = idx;
  29951. }
  29952. return vertexData;
  29953. };
  29954. /**
  29955. * Creates the VertexData of the Box.
  29956. */
  29957. VertexData.CreateBox = function (options) {
  29958. var normalsSource = [
  29959. new BABYLON.Vector3(0, 0, 1),
  29960. new BABYLON.Vector3(0, 0, -1),
  29961. new BABYLON.Vector3(1, 0, 0),
  29962. new BABYLON.Vector3(-1, 0, 0),
  29963. new BABYLON.Vector3(0, 1, 0),
  29964. new BABYLON.Vector3(0, -1, 0)
  29965. ];
  29966. var indices = [];
  29967. var positions = [];
  29968. var normals = [];
  29969. var uvs = [];
  29970. var width = options.width || options.size || 1;
  29971. var height = options.height || options.size || 1;
  29972. var depth = options.depth || options.size || 1;
  29973. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29974. var faceUV = options.faceUV || new Array(6);
  29975. var faceColors = options.faceColors;
  29976. var colors = [];
  29977. // default face colors and UV if undefined
  29978. for (var f = 0; f < 6; f++) {
  29979. if (faceUV[f] === undefined) {
  29980. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29981. }
  29982. if (faceColors && faceColors[f] === undefined) {
  29983. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29984. }
  29985. }
  29986. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29987. // Create each face in turn.
  29988. for (var index = 0; index < normalsSource.length; index++) {
  29989. var normal = normalsSource[index];
  29990. // Get two vectors perpendicular to the face normal and to each other.
  29991. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29992. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29993. // Six indices (two triangles) per face.
  29994. var verticesLength = positions.length / 3;
  29995. indices.push(verticesLength);
  29996. indices.push(verticesLength + 1);
  29997. indices.push(verticesLength + 2);
  29998. indices.push(verticesLength);
  29999. indices.push(verticesLength + 2);
  30000. indices.push(verticesLength + 3);
  30001. // Four vertices per face.
  30002. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30003. positions.push(vertex.x, vertex.y, vertex.z);
  30004. normals.push(normal.x, normal.y, normal.z);
  30005. uvs.push(faceUV[index].z, faceUV[index].w);
  30006. if (faceColors) {
  30007. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30008. }
  30009. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30010. positions.push(vertex.x, vertex.y, vertex.z);
  30011. normals.push(normal.x, normal.y, normal.z);
  30012. uvs.push(faceUV[index].x, faceUV[index].w);
  30013. if (faceColors) {
  30014. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30015. }
  30016. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30017. positions.push(vertex.x, vertex.y, vertex.z);
  30018. normals.push(normal.x, normal.y, normal.z);
  30019. uvs.push(faceUV[index].x, faceUV[index].y);
  30020. if (faceColors) {
  30021. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30022. }
  30023. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30024. positions.push(vertex.x, vertex.y, vertex.z);
  30025. normals.push(normal.x, normal.y, normal.z);
  30026. uvs.push(faceUV[index].z, faceUV[index].y);
  30027. if (faceColors) {
  30028. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30029. }
  30030. }
  30031. // sides
  30032. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30033. // Result
  30034. var vertexData = new VertexData();
  30035. vertexData.indices = indices;
  30036. vertexData.positions = positions;
  30037. vertexData.normals = normals;
  30038. vertexData.uvs = uvs;
  30039. if (faceColors) {
  30040. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30041. vertexData.colors = totalColors;
  30042. }
  30043. return vertexData;
  30044. };
  30045. /**
  30046. * Creates the VertexData of the Sphere.
  30047. */
  30048. VertexData.CreateSphere = function (options) {
  30049. var segments = options.segments || 32;
  30050. var diameterX = options.diameterX || options.diameter || 1;
  30051. var diameterY = options.diameterY || options.diameter || 1;
  30052. var diameterZ = options.diameterZ || options.diameter || 1;
  30053. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30054. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30055. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30056. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30057. var totalZRotationSteps = 2 + segments;
  30058. var totalYRotationSteps = 2 * totalZRotationSteps;
  30059. var indices = [];
  30060. var positions = [];
  30061. var normals = [];
  30062. var uvs = [];
  30063. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30064. var normalizedZ = zRotationStep / totalZRotationSteps;
  30065. var angleZ = normalizedZ * Math.PI * slice;
  30066. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30067. var normalizedY = yRotationStep / totalYRotationSteps;
  30068. var angleY = normalizedY * Math.PI * 2 * arc;
  30069. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30070. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30071. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30072. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30073. var vertex = complete.multiply(radius);
  30074. var normal = complete.divide(radius).normalize();
  30075. positions.push(vertex.x, vertex.y, vertex.z);
  30076. normals.push(normal.x, normal.y, normal.z);
  30077. uvs.push(normalizedY, normalizedZ);
  30078. }
  30079. if (zRotationStep > 0) {
  30080. var verticesCount = positions.length / 3;
  30081. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30082. indices.push((firstIndex));
  30083. indices.push((firstIndex + 1));
  30084. indices.push(firstIndex + totalYRotationSteps + 1);
  30085. indices.push((firstIndex + totalYRotationSteps + 1));
  30086. indices.push((firstIndex + 1));
  30087. indices.push((firstIndex + totalYRotationSteps + 2));
  30088. }
  30089. }
  30090. }
  30091. // Sides
  30092. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30093. // Result
  30094. var vertexData = new VertexData();
  30095. vertexData.indices = indices;
  30096. vertexData.positions = positions;
  30097. vertexData.normals = normals;
  30098. vertexData.uvs = uvs;
  30099. return vertexData;
  30100. };
  30101. /**
  30102. * Creates the VertexData of the Cylinder or Cone.
  30103. */
  30104. VertexData.CreateCylinder = function (options) {
  30105. var height = options.height || 2;
  30106. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30107. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  30108. var tessellation = options.tessellation || 24;
  30109. var subdivisions = options.subdivisions || 1;
  30110. var hasRings = options.hasRings ? true : false;
  30111. var enclose = options.enclose ? true : false;
  30112. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30113. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30114. var faceUV = options.faceUV || new Array(3);
  30115. var faceColors = options.faceColors;
  30116. // default face colors and UV if undefined
  30117. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30118. var ringNb = (hasRings) ? subdivisions : 1;
  30119. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30120. var f;
  30121. for (f = 0; f < surfaceNb; f++) {
  30122. if (faceColors && faceColors[f] === undefined) {
  30123. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30124. }
  30125. }
  30126. for (f = 0; f < surfaceNb; f++) {
  30127. if (faceUV && faceUV[f] === undefined) {
  30128. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30129. }
  30130. }
  30131. var indices = new Array();
  30132. var positions = new Array();
  30133. var normals = new Array();
  30134. var uvs = new Array();
  30135. var colors = new Array();
  30136. var angle_step = Math.PI * 2 * arc / tessellation;
  30137. var angle;
  30138. var h;
  30139. var radius;
  30140. var tan = (diameterBottom - diameterTop) / 2 / height;
  30141. var ringVertex = BABYLON.Vector3.Zero();
  30142. var ringNormal = BABYLON.Vector3.Zero();
  30143. var ringFirstVertex = BABYLON.Vector3.Zero();
  30144. var ringFirstNormal = BABYLON.Vector3.Zero();
  30145. var quadNormal = BABYLON.Vector3.Zero();
  30146. var Y = BABYLON.Axis.Y;
  30147. // positions, normals, uvs
  30148. var i;
  30149. var j;
  30150. var r;
  30151. var ringIdx = 1;
  30152. var s = 1; // surface index
  30153. var cs = 0;
  30154. var v = 0;
  30155. for (i = 0; i <= subdivisions; i++) {
  30156. h = i / subdivisions;
  30157. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30158. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30159. for (r = 0; r < ringIdx; r++) {
  30160. if (hasRings) {
  30161. s += r;
  30162. }
  30163. if (enclose) {
  30164. s += 2 * r;
  30165. }
  30166. for (j = 0; j <= tessellation; j++) {
  30167. angle = j * angle_step;
  30168. // position
  30169. ringVertex.x = Math.cos(-angle) * radius;
  30170. ringVertex.y = -height / 2 + h * height;
  30171. ringVertex.z = Math.sin(-angle) * radius;
  30172. // normal
  30173. if (diameterTop === 0 && i === subdivisions) {
  30174. // if no top cap, reuse former normals
  30175. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30176. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30177. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30178. }
  30179. else {
  30180. ringNormal.x = ringVertex.x;
  30181. ringNormal.z = ringVertex.z;
  30182. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30183. ringNormal.normalize();
  30184. }
  30185. // keep first ring vertex values for enclose
  30186. if (j === 0) {
  30187. ringFirstVertex.copyFrom(ringVertex);
  30188. ringFirstNormal.copyFrom(ringNormal);
  30189. }
  30190. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30191. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30192. if (hasRings) {
  30193. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30194. }
  30195. else {
  30196. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30197. }
  30198. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30199. if (faceColors) {
  30200. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30201. }
  30202. }
  30203. // if enclose, add four vertices and their dedicated normals
  30204. if (arc !== 1 && enclose) {
  30205. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30206. positions.push(0, ringVertex.y, 0);
  30207. positions.push(0, ringVertex.y, 0);
  30208. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30209. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30210. quadNormal.normalize();
  30211. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30212. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30213. quadNormal.normalize();
  30214. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30215. if (hasRings) {
  30216. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30217. }
  30218. else {
  30219. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30220. }
  30221. uvs.push(faceUV[s + 1].x, v);
  30222. uvs.push(faceUV[s + 1].z, v);
  30223. if (hasRings) {
  30224. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30225. }
  30226. else {
  30227. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30228. }
  30229. uvs.push(faceUV[s + 2].x, v);
  30230. uvs.push(faceUV[s + 2].z, v);
  30231. if (faceColors) {
  30232. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30233. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30234. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30235. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30236. }
  30237. }
  30238. if (cs !== s) {
  30239. cs = s;
  30240. }
  30241. }
  30242. }
  30243. // indices
  30244. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30245. var s;
  30246. i = 0;
  30247. for (s = 0; s < subdivisions; s++) {
  30248. var i0 = 0;
  30249. var i1 = 0;
  30250. var i2 = 0;
  30251. var i3 = 0;
  30252. for (j = 0; j < tessellation; j++) {
  30253. i0 = i * (e + 1) + j;
  30254. i1 = (i + 1) * (e + 1) + j;
  30255. i2 = i * (e + 1) + (j + 1);
  30256. i3 = (i + 1) * (e + 1) + (j + 1);
  30257. indices.push(i0, i1, i2);
  30258. indices.push(i3, i2, i1);
  30259. }
  30260. if (arc !== 1 && enclose) {
  30261. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30262. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30263. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30264. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30265. }
  30266. i = (hasRings) ? (i + 2) : (i + 1);
  30267. }
  30268. // Caps
  30269. var createCylinderCap = function (isTop) {
  30270. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30271. if (radius === 0) {
  30272. return;
  30273. }
  30274. // Cap positions, normals & uvs
  30275. var angle;
  30276. var circleVector;
  30277. var i;
  30278. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30279. var c = null;
  30280. if (faceColors) {
  30281. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30282. }
  30283. // cap center
  30284. var vbase = positions.length / 3;
  30285. var offset = isTop ? height / 2 : -height / 2;
  30286. var center = new BABYLON.Vector3(0, offset, 0);
  30287. positions.push(center.x, center.y, center.z);
  30288. normals.push(0, isTop ? 1 : -1, 0);
  30289. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30290. if (c) {
  30291. colors.push(c.r, c.g, c.b, c.a);
  30292. }
  30293. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30294. for (i = 0; i <= tessellation; i++) {
  30295. angle = Math.PI * 2 * i * arc / tessellation;
  30296. var cos = Math.cos(-angle);
  30297. var sin = Math.sin(-angle);
  30298. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30299. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30300. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30301. normals.push(0, isTop ? 1 : -1, 0);
  30302. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30303. if (c) {
  30304. colors.push(c.r, c.g, c.b, c.a);
  30305. }
  30306. }
  30307. // Cap indices
  30308. for (i = 0; i < tessellation; i++) {
  30309. if (!isTop) {
  30310. indices.push(vbase);
  30311. indices.push(vbase + (i + 1));
  30312. indices.push(vbase + (i + 2));
  30313. }
  30314. else {
  30315. indices.push(vbase);
  30316. indices.push(vbase + (i + 2));
  30317. indices.push(vbase + (i + 1));
  30318. }
  30319. }
  30320. };
  30321. // add caps to geometry
  30322. createCylinderCap(false);
  30323. createCylinderCap(true);
  30324. // Sides
  30325. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30326. var vertexData = new VertexData();
  30327. vertexData.indices = indices;
  30328. vertexData.positions = positions;
  30329. vertexData.normals = normals;
  30330. vertexData.uvs = uvs;
  30331. if (faceColors) {
  30332. vertexData.colors = colors;
  30333. }
  30334. return vertexData;
  30335. };
  30336. /**
  30337. * Creates the VertexData of the Torus.
  30338. */
  30339. VertexData.CreateTorus = function (options) {
  30340. var indices = [];
  30341. var positions = [];
  30342. var normals = [];
  30343. var uvs = [];
  30344. var diameter = options.diameter || 1;
  30345. var thickness = options.thickness || 0.5;
  30346. var tessellation = options.tessellation || 16;
  30347. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30348. var stride = tessellation + 1;
  30349. for (var i = 0; i <= tessellation; i++) {
  30350. var u = i / tessellation;
  30351. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30352. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30353. for (var j = 0; j <= tessellation; j++) {
  30354. var v = 1 - j / tessellation;
  30355. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30356. var dx = Math.cos(innerAngle);
  30357. var dy = Math.sin(innerAngle);
  30358. // Create a vertex.
  30359. var normal = new BABYLON.Vector3(dx, dy, 0);
  30360. var position = normal.scale(thickness / 2);
  30361. var textureCoordinate = new BABYLON.Vector2(u, v);
  30362. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30363. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30364. positions.push(position.x, position.y, position.z);
  30365. normals.push(normal.x, normal.y, normal.z);
  30366. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30367. // And create indices for two triangles.
  30368. var nextI = (i + 1) % stride;
  30369. var nextJ = (j + 1) % stride;
  30370. indices.push(i * stride + j);
  30371. indices.push(i * stride + nextJ);
  30372. indices.push(nextI * stride + j);
  30373. indices.push(i * stride + nextJ);
  30374. indices.push(nextI * stride + nextJ);
  30375. indices.push(nextI * stride + j);
  30376. }
  30377. }
  30378. // Sides
  30379. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30380. // Result
  30381. var vertexData = new VertexData();
  30382. vertexData.indices = indices;
  30383. vertexData.positions = positions;
  30384. vertexData.normals = normals;
  30385. vertexData.uvs = uvs;
  30386. return vertexData;
  30387. };
  30388. /**
  30389. * Creates the VertexData of the LineSystem.
  30390. */
  30391. VertexData.CreateLineSystem = function (options) {
  30392. var indices = [];
  30393. var positions = [];
  30394. var lines = options.lines;
  30395. var colors = options.colors;
  30396. var vertexColors = [];
  30397. var idx = 0;
  30398. for (var l = 0; l < lines.length; l++) {
  30399. var points = lines[l];
  30400. for (var index = 0; index < points.length; index++) {
  30401. positions.push(points[index].x, points[index].y, points[index].z);
  30402. if (colors) {
  30403. var color = colors[l];
  30404. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  30405. }
  30406. if (index > 0) {
  30407. indices.push(idx - 1);
  30408. indices.push(idx);
  30409. }
  30410. idx++;
  30411. }
  30412. }
  30413. var vertexData = new VertexData();
  30414. vertexData.indices = indices;
  30415. vertexData.positions = positions;
  30416. if (colors) {
  30417. vertexData.colors = vertexColors;
  30418. }
  30419. return vertexData;
  30420. };
  30421. /**
  30422. * Create the VertexData of the DashedLines.
  30423. */
  30424. VertexData.CreateDashedLines = function (options) {
  30425. var dashSize = options.dashSize || 3;
  30426. var gapSize = options.gapSize || 1;
  30427. var dashNb = options.dashNb || 200;
  30428. var points = options.points;
  30429. var positions = new Array();
  30430. var indices = new Array();
  30431. var curvect = BABYLON.Vector3.Zero();
  30432. var lg = 0;
  30433. var nb = 0;
  30434. var shft = 0;
  30435. var dashshft = 0;
  30436. var curshft = 0;
  30437. var idx = 0;
  30438. var i = 0;
  30439. for (i = 0; i < points.length - 1; i++) {
  30440. points[i + 1].subtractToRef(points[i], curvect);
  30441. lg += curvect.length();
  30442. }
  30443. shft = lg / dashNb;
  30444. dashshft = dashSize * shft / (dashSize + gapSize);
  30445. for (i = 0; i < points.length - 1; i++) {
  30446. points[i + 1].subtractToRef(points[i], curvect);
  30447. nb = Math.floor(curvect.length() / shft);
  30448. curvect.normalize();
  30449. for (var j = 0; j < nb; j++) {
  30450. curshft = shft * j;
  30451. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30452. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30453. indices.push(idx, idx + 1);
  30454. idx += 2;
  30455. }
  30456. }
  30457. // Result
  30458. var vertexData = new VertexData();
  30459. vertexData.positions = positions;
  30460. vertexData.indices = indices;
  30461. return vertexData;
  30462. };
  30463. /**
  30464. * Creates the VertexData of the Ground.
  30465. */
  30466. VertexData.CreateGround = function (options) {
  30467. var indices = [];
  30468. var positions = [];
  30469. var normals = [];
  30470. var uvs = [];
  30471. var row, col;
  30472. var width = options.width || 1;
  30473. var height = options.height || 1;
  30474. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  30475. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  30476. for (row = 0; row <= subdivisionsY; row++) {
  30477. for (col = 0; col <= subdivisionsX; col++) {
  30478. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  30479. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30480. positions.push(position.x, position.y, position.z);
  30481. normals.push(normal.x, normal.y, normal.z);
  30482. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  30483. }
  30484. }
  30485. for (row = 0; row < subdivisionsY; row++) {
  30486. for (col = 0; col < subdivisionsX; col++) {
  30487. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30488. indices.push(col + 1 + row * (subdivisionsX + 1));
  30489. indices.push(col + row * (subdivisionsX + 1));
  30490. indices.push(col + (row + 1) * (subdivisionsX + 1));
  30491. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30492. indices.push(col + row * (subdivisionsX + 1));
  30493. }
  30494. }
  30495. // Result
  30496. var vertexData = new VertexData();
  30497. vertexData.indices = indices;
  30498. vertexData.positions = positions;
  30499. vertexData.normals = normals;
  30500. vertexData.uvs = uvs;
  30501. return vertexData;
  30502. };
  30503. /**
  30504. * Creates the VertexData of the TiledGround.
  30505. */
  30506. VertexData.CreateTiledGround = function (options) {
  30507. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  30508. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  30509. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  30510. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  30511. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30512. var precision = options.precision || { w: 1, h: 1 };
  30513. var indices = new Array();
  30514. var positions = new Array();
  30515. var normals = new Array();
  30516. var uvs = new Array();
  30517. var row, col, tileRow, tileCol;
  30518. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30519. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30520. precision.w = (precision.w < 1) ? 1 : precision.w;
  30521. precision.h = (precision.h < 1) ? 1 : precision.h;
  30522. var tileSize = {
  30523. 'w': (xmax - xmin) / subdivisions.w,
  30524. 'h': (zmax - zmin) / subdivisions.h
  30525. };
  30526. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30527. // Indices
  30528. var base = positions.length / 3;
  30529. var rowLength = precision.w + 1;
  30530. for (row = 0; row < precision.h; row++) {
  30531. for (col = 0; col < precision.w; col++) {
  30532. var square = [
  30533. base + col + row * rowLength,
  30534. base + (col + 1) + row * rowLength,
  30535. base + (col + 1) + (row + 1) * rowLength,
  30536. base + col + (row + 1) * rowLength
  30537. ];
  30538. indices.push(square[1]);
  30539. indices.push(square[2]);
  30540. indices.push(square[3]);
  30541. indices.push(square[0]);
  30542. indices.push(square[1]);
  30543. indices.push(square[3]);
  30544. }
  30545. }
  30546. // Position, normals and uvs
  30547. var position = BABYLON.Vector3.Zero();
  30548. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30549. for (row = 0; row <= precision.h; row++) {
  30550. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30551. for (col = 0; col <= precision.w; col++) {
  30552. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30553. position.y = 0;
  30554. positions.push(position.x, position.y, position.z);
  30555. normals.push(normal.x, normal.y, normal.z);
  30556. uvs.push(col / precision.w, row / precision.h);
  30557. }
  30558. }
  30559. }
  30560. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30561. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30562. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30563. }
  30564. }
  30565. // Result
  30566. var vertexData = new VertexData();
  30567. vertexData.indices = indices;
  30568. vertexData.positions = positions;
  30569. vertexData.normals = normals;
  30570. vertexData.uvs = uvs;
  30571. return vertexData;
  30572. };
  30573. /**
  30574. * Creates the VertexData of the Ground designed from a heightmap.
  30575. */
  30576. VertexData.CreateGroundFromHeightMap = function (options) {
  30577. var indices = [];
  30578. var positions = [];
  30579. var normals = [];
  30580. var uvs = [];
  30581. var row, col;
  30582. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  30583. // Vertices
  30584. for (row = 0; row <= options.subdivisions; row++) {
  30585. for (col = 0; col <= options.subdivisions; col++) {
  30586. 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));
  30587. // Compute height
  30588. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30589. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30590. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30591. var r = options.buffer[pos] / 255.0;
  30592. var g = options.buffer[pos + 1] / 255.0;
  30593. var b = options.buffer[pos + 2] / 255.0;
  30594. var gradient = r * filter.r + g * filter.g + b * filter.b;
  30595. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30596. // Add vertex
  30597. positions.push(position.x, position.y, position.z);
  30598. normals.push(0, 0, 0);
  30599. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30600. }
  30601. }
  30602. // Indices
  30603. for (row = 0; row < options.subdivisions; row++) {
  30604. for (col = 0; col < options.subdivisions; col++) {
  30605. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30606. indices.push(col + 1 + row * (options.subdivisions + 1));
  30607. indices.push(col + row * (options.subdivisions + 1));
  30608. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30609. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30610. indices.push(col + row * (options.subdivisions + 1));
  30611. }
  30612. }
  30613. // Normals
  30614. VertexData.ComputeNormals(positions, indices, normals);
  30615. // Result
  30616. var vertexData = new VertexData();
  30617. vertexData.indices = indices;
  30618. vertexData.positions = positions;
  30619. vertexData.normals = normals;
  30620. vertexData.uvs = uvs;
  30621. return vertexData;
  30622. };
  30623. /**
  30624. * Creates the VertexData of the Plane.
  30625. */
  30626. VertexData.CreatePlane = function (options) {
  30627. var indices = [];
  30628. var positions = [];
  30629. var normals = [];
  30630. var uvs = [];
  30631. var width = options.width || options.size || 1;
  30632. var height = options.height || options.size || 1;
  30633. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30634. // Vertices
  30635. var halfWidth = width / 2.0;
  30636. var halfHeight = height / 2.0;
  30637. positions.push(-halfWidth, -halfHeight, 0);
  30638. normals.push(0, 0, -1.0);
  30639. uvs.push(0.0, 0.0);
  30640. positions.push(halfWidth, -halfHeight, 0);
  30641. normals.push(0, 0, -1.0);
  30642. uvs.push(1.0, 0.0);
  30643. positions.push(halfWidth, halfHeight, 0);
  30644. normals.push(0, 0, -1.0);
  30645. uvs.push(1.0, 1.0);
  30646. positions.push(-halfWidth, halfHeight, 0);
  30647. normals.push(0, 0, -1.0);
  30648. uvs.push(0.0, 1.0);
  30649. // Indices
  30650. indices.push(0);
  30651. indices.push(1);
  30652. indices.push(2);
  30653. indices.push(0);
  30654. indices.push(2);
  30655. indices.push(3);
  30656. // Sides
  30657. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30658. // Result
  30659. var vertexData = new VertexData();
  30660. vertexData.indices = indices;
  30661. vertexData.positions = positions;
  30662. vertexData.normals = normals;
  30663. vertexData.uvs = uvs;
  30664. return vertexData;
  30665. };
  30666. /**
  30667. * Creates the VertexData of the Disc or regular Polygon.
  30668. */
  30669. VertexData.CreateDisc = function (options) {
  30670. var positions = new Array();
  30671. var indices = new Array();
  30672. var normals = new Array();
  30673. var uvs = new Array();
  30674. var radius = options.radius || 0.5;
  30675. var tessellation = options.tessellation || 64;
  30676. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30677. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30678. // positions and uvs
  30679. positions.push(0, 0, 0); // disc center first
  30680. uvs.push(0.5, 0.5);
  30681. var theta = Math.PI * 2 * arc;
  30682. var step = theta / tessellation;
  30683. for (var a = 0; a < theta; a += step) {
  30684. var x = Math.cos(a);
  30685. var y = Math.sin(a);
  30686. var u = (x + 1) / 2;
  30687. var v = (1 - y) / 2;
  30688. positions.push(radius * x, radius * y, 0);
  30689. uvs.push(u, v);
  30690. }
  30691. if (arc === 1) {
  30692. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30693. uvs.push(uvs[2], uvs[3]);
  30694. }
  30695. //indices
  30696. var vertexNb = positions.length / 3;
  30697. for (var i = 1; i < vertexNb - 1; i++) {
  30698. indices.push(i + 1, 0, i);
  30699. }
  30700. // result
  30701. VertexData.ComputeNormals(positions, indices, normals);
  30702. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30703. var vertexData = new VertexData();
  30704. vertexData.indices = indices;
  30705. vertexData.positions = positions;
  30706. vertexData.normals = normals;
  30707. vertexData.uvs = uvs;
  30708. return vertexData;
  30709. };
  30710. /**
  30711. * Re-creates the VertexData of the Polygon for sideOrientation.
  30712. */
  30713. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30714. var faceUV = fUV || new Array(3);
  30715. var faceColors = fColors;
  30716. var colors = [];
  30717. // default face colors and UV if undefined
  30718. for (var f = 0; f < 3; f++) {
  30719. if (faceUV[f] === undefined) {
  30720. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30721. }
  30722. if (faceColors && faceColors[f] === undefined) {
  30723. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30724. }
  30725. }
  30726. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30727. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30728. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30729. var indices = polygon.getIndices();
  30730. // set face colours and textures
  30731. var idx = 0;
  30732. var face = 0;
  30733. for (var index = 0; index < normals.length; index += 3) {
  30734. //Edge Face no. 1
  30735. if (Math.abs(normals[index + 1]) < 0.001) {
  30736. face = 1;
  30737. }
  30738. //Top Face no. 0
  30739. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30740. face = 0;
  30741. }
  30742. //Bottom Face no. 2
  30743. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30744. face = 2;
  30745. }
  30746. idx = index / 3;
  30747. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30748. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30749. if (faceColors) {
  30750. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30751. }
  30752. }
  30753. // sides
  30754. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30755. // Result
  30756. var vertexData = new VertexData();
  30757. vertexData.indices = indices;
  30758. vertexData.positions = positions;
  30759. vertexData.normals = normals;
  30760. vertexData.uvs = uvs;
  30761. if (faceColors) {
  30762. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30763. vertexData.colors = totalColors;
  30764. }
  30765. return vertexData;
  30766. };
  30767. /**
  30768. * Creates the VertexData of the IcoSphere.
  30769. */
  30770. VertexData.CreateIcoSphere = function (options) {
  30771. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30772. var radius = options.radius || 1;
  30773. var flat = (options.flat === undefined) ? true : options.flat;
  30774. var subdivisions = options.subdivisions || 4;
  30775. var radiusX = options.radiusX || radius;
  30776. var radiusY = options.radiusY || radius;
  30777. var radiusZ = options.radiusZ || radius;
  30778. var t = (1 + Math.sqrt(5)) / 2;
  30779. // 12 vertex x,y,z
  30780. var ico_vertices = [
  30781. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30782. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30783. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30784. ];
  30785. // index of 3 vertex makes a face of icopshere
  30786. var ico_indices = [
  30787. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30788. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30789. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30790. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30791. ];
  30792. // vertex for uv have aliased position, not for UV
  30793. var vertices_unalias_id = [
  30794. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30795. // vertex alias
  30796. 0,
  30797. 2,
  30798. 3,
  30799. 3,
  30800. 3,
  30801. 4,
  30802. 7,
  30803. 8,
  30804. 9,
  30805. 9,
  30806. 10,
  30807. 11 // 23: B + 12
  30808. ];
  30809. // uv as integer step (not pixels !)
  30810. var ico_vertexuv = [
  30811. 5, 1, 3, 1, 6, 4, 0, 0,
  30812. 5, 3, 4, 2, 2, 2, 4, 0,
  30813. 2, 0, 1, 1, 6, 0, 6, 2,
  30814. // vertex alias (for same vertex on different faces)
  30815. 0, 4,
  30816. 3, 3,
  30817. 4, 4,
  30818. 3, 1,
  30819. 4, 2,
  30820. 4, 4,
  30821. 0, 2,
  30822. 1, 1,
  30823. 2, 2,
  30824. 3, 3,
  30825. 1, 3,
  30826. 2, 4 // 23: B + 12
  30827. ];
  30828. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30829. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30830. // First island of uv mapping
  30831. // v = 4h 3+ 2
  30832. // v = 3h 9+ 4
  30833. // v = 2h 9+ 5 B
  30834. // v = 1h 9 1 0
  30835. // v = 0h 3 8 7 A
  30836. // u = 0 1 2 3 4 5 6 *a
  30837. // Second island of uv mapping
  30838. // v = 4h 0+ B+ 4+
  30839. // v = 3h A+ 2+
  30840. // v = 2h 7+ 6 3+
  30841. // v = 1h 8+ 3+
  30842. // v = 0h
  30843. // u = 0 1 2 3 4 5 6 *a
  30844. // Face layout on texture UV mapping
  30845. // ============
  30846. // \ 4 /\ 16 / ======
  30847. // \ / \ / /\ 11 /
  30848. // \/ 7 \/ / \ /
  30849. // ======= / 10 \/
  30850. // /\ 17 /\ =======
  30851. // / \ / \ \ 15 /\
  30852. // / 8 \/ 12 \ \ / \
  30853. // ============ \/ 6 \
  30854. // \ 18 /\ ============
  30855. // \ / \ \ 5 /\ 0 /
  30856. // \/ 13 \ \ / \ /
  30857. // ======= \/ 1 \/
  30858. // =============
  30859. // /\ 19 /\ 2 /\
  30860. // / \ / \ / \
  30861. // / 14 \/ 9 \/ 3 \
  30862. // ===================
  30863. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30864. var ustep = 138 / 1024;
  30865. var vstep = 239 / 1024;
  30866. var uoffset = 60 / 1024;
  30867. var voffset = 26 / 1024;
  30868. // Second island should have margin, not to touch the first island
  30869. // avoid any borderline artefact in pixel rounding
  30870. var island_u_offset = -40 / 1024;
  30871. var island_v_offset = +20 / 1024;
  30872. // face is either island 0 or 1 :
  30873. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30874. var island = [
  30875. 0, 0, 0, 0, 1,
  30876. 0, 0, 1, 1, 0,
  30877. 0, 0, 1, 1, 0,
  30878. 0, 1, 1, 1, 0 // 15 - 19
  30879. ];
  30880. var indices = new Array();
  30881. var positions = new Array();
  30882. var normals = new Array();
  30883. var uvs = new Array();
  30884. var current_indice = 0;
  30885. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30886. var face_vertex_pos = new Array(3);
  30887. var face_vertex_uv = new Array(3);
  30888. var v012;
  30889. for (v012 = 0; v012 < 3; v012++) {
  30890. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30891. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30892. }
  30893. // create all with normals
  30894. for (var face = 0; face < 20; face++) {
  30895. // 3 vertex per face
  30896. for (v012 = 0; v012 < 3; v012++) {
  30897. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30898. var v_id = ico_indices[3 * face + v012];
  30899. // vertex have 3D position (x,y,z)
  30900. 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]);
  30901. // Normalize to get normal, then scale to radius
  30902. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30903. // uv Coordinates from vertex ID
  30904. 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);
  30905. }
  30906. // Subdivide the face (interpolate pos, norm, uv)
  30907. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30908. // - norm is linear interpolation of vertex corner normal
  30909. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30910. // - uv is linear interpolation
  30911. //
  30912. // Topology is as below for sub-divide by 2
  30913. // vertex shown as v0,v1,v2
  30914. // interp index is i1 to progress in range [v0,v1[
  30915. // interp index is i2 to progress in range [v0,v2[
  30916. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30917. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30918. //
  30919. //
  30920. // i2 v2
  30921. // ^ ^
  30922. // / / \
  30923. // / / \
  30924. // / / \
  30925. // / / (0,1) \
  30926. // / #---------\
  30927. // / / \ (0,0)'/ \
  30928. // / / \ / \
  30929. // / / \ / \
  30930. // / / (0,0) \ / (1,0) \
  30931. // / #---------#---------\
  30932. // v0 v1
  30933. //
  30934. // --------------------> i1
  30935. //
  30936. // interp of (i1,i2):
  30937. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30938. // along i1 : lerp(x0,x1, i1/(S-i2))
  30939. //
  30940. // centroid of triangle is needed to get help normal computation
  30941. // (c1,c2) are used for centroid location
  30942. var interp_vertex = function (i1, i2, c1, c2) {
  30943. // vertex is interpolated from
  30944. // - face_vertex_pos[0..2]
  30945. // - face_vertex_uv[0..2]
  30946. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30947. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30948. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30949. pos_interp.normalize();
  30950. var vertex_normal;
  30951. if (flat) {
  30952. // in flat mode, recalculate normal as face centroid normal
  30953. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30954. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30955. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30956. }
  30957. else {
  30958. // in smooth mode, recalculate normal from each single vertex position
  30959. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30960. }
  30961. // Vertex normal need correction due to X,Y,Z radius scaling
  30962. vertex_normal.x /= radiusX;
  30963. vertex_normal.y /= radiusY;
  30964. vertex_normal.z /= radiusZ;
  30965. vertex_normal.normalize();
  30966. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30967. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30968. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30969. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30970. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30971. uvs.push(uv_interp.x, uv_interp.y);
  30972. // push each vertex has member of a face
  30973. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30974. indices.push(current_indice);
  30975. current_indice++;
  30976. };
  30977. for (var i2 = 0; i2 < subdivisions; i2++) {
  30978. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30979. // face : (i1,i2) for /\ :
  30980. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30981. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30982. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30983. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30984. if (i1 + i2 + 1 < subdivisions) {
  30985. // face : (i1,i2)' for \/ :
  30986. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30987. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30988. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30989. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30990. }
  30991. }
  30992. }
  30993. }
  30994. // Sides
  30995. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30996. // Result
  30997. var vertexData = new VertexData();
  30998. vertexData.indices = indices;
  30999. vertexData.positions = positions;
  31000. vertexData.normals = normals;
  31001. vertexData.uvs = uvs;
  31002. return vertexData;
  31003. };
  31004. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31005. /**
  31006. * Creates the VertexData of the Polyhedron.
  31007. */
  31008. VertexData.CreatePolyhedron = function (options) {
  31009. // provided polyhedron types :
  31010. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31011. // 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)
  31012. var polyhedra = [];
  31013. 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]] };
  31014. 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]] };
  31015. polyhedra[2] = {
  31016. 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]],
  31017. 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]]
  31018. };
  31019. polyhedra[3] = {
  31020. 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]],
  31021. 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]]
  31022. };
  31023. polyhedra[4] = {
  31024. 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]],
  31025. 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]]
  31026. };
  31027. 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]] };
  31028. 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]] };
  31029. 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]] };
  31030. 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]] };
  31031. 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]] };
  31032. 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]] };
  31033. 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]] };
  31034. 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]] };
  31035. 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]] };
  31036. polyhedra[14] = {
  31037. 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]],
  31038. 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]]
  31039. };
  31040. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31041. var size = options.size;
  31042. var sizeX = options.sizeX || size || 1;
  31043. var sizeY = options.sizeY || size || 1;
  31044. var sizeZ = options.sizeZ || size || 1;
  31045. var data = options.custom || polyhedra[type];
  31046. var nbfaces = data.face.length;
  31047. var faceUV = options.faceUV || new Array(nbfaces);
  31048. var faceColors = options.faceColors;
  31049. var flat = (options.flat === undefined) ? true : options.flat;
  31050. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31051. var positions = new Array();
  31052. var indices = new Array();
  31053. var normals = new Array();
  31054. var uvs = new Array();
  31055. var colors = new Array();
  31056. var index = 0;
  31057. var faceIdx = 0; // face cursor in the array "indexes"
  31058. var indexes = new Array();
  31059. var i = 0;
  31060. var f = 0;
  31061. var u, v, ang, x, y, tmp;
  31062. // default face colors and UV if undefined
  31063. if (flat) {
  31064. for (f = 0; f < nbfaces; f++) {
  31065. if (faceColors && faceColors[f] === undefined) {
  31066. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31067. }
  31068. if (faceUV && faceUV[f] === undefined) {
  31069. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31070. }
  31071. }
  31072. }
  31073. if (!flat) {
  31074. for (i = 0; i < data.vertex.length; i++) {
  31075. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31076. uvs.push(0, 0);
  31077. }
  31078. for (f = 0; f < nbfaces; f++) {
  31079. for (i = 0; i < data.face[f].length - 2; i++) {
  31080. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31081. }
  31082. }
  31083. }
  31084. else {
  31085. for (f = 0; f < nbfaces; f++) {
  31086. var fl = data.face[f].length; // number of vertices of the current face
  31087. ang = 2 * Math.PI / fl;
  31088. x = 0.5 * Math.tan(ang / 2);
  31089. y = 0.5;
  31090. // positions, uvs, colors
  31091. for (i = 0; i < fl; i++) {
  31092. // positions
  31093. 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);
  31094. indexes.push(index);
  31095. index++;
  31096. // uvs
  31097. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31098. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31099. uvs.push(u, v);
  31100. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31101. y = x * Math.sin(ang) + y * Math.cos(ang);
  31102. x = tmp;
  31103. // colors
  31104. if (faceColors) {
  31105. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31106. }
  31107. }
  31108. // indices from indexes
  31109. for (i = 0; i < fl - 2; i++) {
  31110. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31111. }
  31112. faceIdx += fl;
  31113. }
  31114. }
  31115. VertexData.ComputeNormals(positions, indices, normals);
  31116. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31117. var vertexData = new VertexData();
  31118. vertexData.positions = positions;
  31119. vertexData.indices = indices;
  31120. vertexData.normals = normals;
  31121. vertexData.uvs = uvs;
  31122. if (faceColors && flat) {
  31123. vertexData.colors = colors;
  31124. }
  31125. return vertexData;
  31126. };
  31127. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31128. /**
  31129. * Creates the VertexData of the Torus Knot.
  31130. */
  31131. VertexData.CreateTorusKnot = function (options) {
  31132. var indices = new Array();
  31133. var positions = new Array();
  31134. var normals = new Array();
  31135. var uvs = new Array();
  31136. var radius = options.radius || 2;
  31137. var tube = options.tube || 0.5;
  31138. var radialSegments = options.radialSegments || 32;
  31139. var tubularSegments = options.tubularSegments || 32;
  31140. var p = options.p || 2;
  31141. var q = options.q || 3;
  31142. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31143. // Helper
  31144. var getPos = function (angle) {
  31145. var cu = Math.cos(angle);
  31146. var su = Math.sin(angle);
  31147. var quOverP = q / p * angle;
  31148. var cs = Math.cos(quOverP);
  31149. var tx = radius * (2 + cs) * 0.5 * cu;
  31150. var ty = radius * (2 + cs) * su * 0.5;
  31151. var tz = radius * Math.sin(quOverP) * 0.5;
  31152. return new BABYLON.Vector3(tx, ty, tz);
  31153. };
  31154. // Vertices
  31155. var i;
  31156. var j;
  31157. for (i = 0; i <= radialSegments; i++) {
  31158. var modI = i % radialSegments;
  31159. var u = modI / radialSegments * 2 * p * Math.PI;
  31160. var p1 = getPos(u);
  31161. var p2 = getPos(u + 0.01);
  31162. var tang = p2.subtract(p1);
  31163. var n = p2.add(p1);
  31164. var bitan = BABYLON.Vector3.Cross(tang, n);
  31165. n = BABYLON.Vector3.Cross(bitan, tang);
  31166. bitan.normalize();
  31167. n.normalize();
  31168. for (j = 0; j < tubularSegments; j++) {
  31169. var modJ = j % tubularSegments;
  31170. var v = modJ / tubularSegments * 2 * Math.PI;
  31171. var cx = -tube * Math.cos(v);
  31172. var cy = tube * Math.sin(v);
  31173. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31174. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31175. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31176. uvs.push(i / radialSegments);
  31177. uvs.push(j / tubularSegments);
  31178. }
  31179. }
  31180. for (i = 0; i < radialSegments; i++) {
  31181. for (j = 0; j < tubularSegments; j++) {
  31182. var jNext = (j + 1) % tubularSegments;
  31183. var a = i * tubularSegments + j;
  31184. var b = (i + 1) * tubularSegments + j;
  31185. var c = (i + 1) * tubularSegments + jNext;
  31186. var d = i * tubularSegments + jNext;
  31187. indices.push(d);
  31188. indices.push(b);
  31189. indices.push(a);
  31190. indices.push(d);
  31191. indices.push(c);
  31192. indices.push(b);
  31193. }
  31194. }
  31195. // Normals
  31196. VertexData.ComputeNormals(positions, indices, normals);
  31197. // Sides
  31198. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31199. // Result
  31200. var vertexData = new VertexData();
  31201. vertexData.indices = indices;
  31202. vertexData.positions = positions;
  31203. vertexData.normals = normals;
  31204. vertexData.uvs = uvs;
  31205. return vertexData;
  31206. };
  31207. // Tools
  31208. /**
  31209. * @param {any} - positions (number[] or Float32Array)
  31210. * @param {any} - indices (number[] or Uint16Array)
  31211. * @param {any} - normals (number[] or Float32Array)
  31212. * options (optional) :
  31213. * facetPositions : optional array of facet positions (vector3)
  31214. * facetNormals : optional array of facet normals (vector3)
  31215. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  31216. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  31217. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  31218. * bbSize : optional bounding box size data, required for facetPartitioning computation
  31219. * bInfo : optional bounding info, required for facetPartitioning computation
  31220. * useRightHandedSystem: optional boolean to for right handed system computation
  31221. * depthSort : optional boolean to enable the facet depth sort computation
  31222. * distanceTo : optional Vector3 to compute the facet depth from this location
  31223. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  31224. */
  31225. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  31226. // temporary scalar variables
  31227. var index = 0; // facet index
  31228. var p1p2x = 0.0; // p1p2 vector x coordinate
  31229. var p1p2y = 0.0; // p1p2 vector y coordinate
  31230. var p1p2z = 0.0; // p1p2 vector z coordinate
  31231. var p3p2x = 0.0; // p3p2 vector x coordinate
  31232. var p3p2y = 0.0; // p3p2 vector y coordinate
  31233. var p3p2z = 0.0; // p3p2 vector z coordinate
  31234. var faceNormalx = 0.0; // facet normal x coordinate
  31235. var faceNormaly = 0.0; // facet normal y coordinate
  31236. var faceNormalz = 0.0; // facet normal z coordinate
  31237. var length = 0.0; // facet normal length before normalization
  31238. var v1x = 0; // vector1 x index in the positions array
  31239. var v1y = 0; // vector1 y index in the positions array
  31240. var v1z = 0; // vector1 z index in the positions array
  31241. var v2x = 0; // vector2 x index in the positions array
  31242. var v2y = 0; // vector2 y index in the positions array
  31243. var v2z = 0; // vector2 z index in the positions array
  31244. var v3x = 0; // vector3 x index in the positions array
  31245. var v3y = 0; // vector3 y index in the positions array
  31246. var v3z = 0; // vector3 z index in the positions array
  31247. var computeFacetNormals = false;
  31248. var computeFacetPositions = false;
  31249. var computeFacetPartitioning = false;
  31250. var computeDepthSort = false;
  31251. var faceNormalSign = 1;
  31252. var ratio = 0;
  31253. var distanceTo = null;
  31254. if (options) {
  31255. computeFacetNormals = (options.facetNormals) ? true : false;
  31256. computeFacetPositions = (options.facetPositions) ? true : false;
  31257. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  31258. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  31259. ratio = options.ratio || 0;
  31260. computeDepthSort = (options.depthSort) ? true : false;
  31261. distanceTo = (options.distanceTo);
  31262. if (computeDepthSort) {
  31263. if (distanceTo === undefined) {
  31264. distanceTo = BABYLON.Vector3.Zero();
  31265. }
  31266. var depthSortedFacets = options.depthSortedFacets;
  31267. }
  31268. }
  31269. // facetPartitioning reinit if needed
  31270. var xSubRatio = 0;
  31271. var ySubRatio = 0;
  31272. var zSubRatio = 0;
  31273. var subSq = 0;
  31274. if (computeFacetPartitioning && options && options.bbSize) {
  31275. var ox = 0; // X partitioning index for facet position
  31276. var oy = 0; // Y partinioning index for facet position
  31277. var oz = 0; // Z partinioning index for facet position
  31278. var b1x = 0; // X partitioning index for facet v1 vertex
  31279. var b1y = 0; // Y partitioning index for facet v1 vertex
  31280. var b1z = 0; // z partitioning index for facet v1 vertex
  31281. var b2x = 0; // X partitioning index for facet v2 vertex
  31282. var b2y = 0; // Y partitioning index for facet v2 vertex
  31283. var b2z = 0; // Z partitioning index for facet v2 vertex
  31284. var b3x = 0; // X partitioning index for facet v3 vertex
  31285. var b3y = 0; // Y partitioning index for facet v3 vertex
  31286. var b3z = 0; // Z partitioning index for facet v3 vertex
  31287. var block_idx_o = 0; // facet barycenter block index
  31288. var block_idx_v1 = 0; // v1 vertex block index
  31289. var block_idx_v2 = 0; // v2 vertex block index
  31290. var block_idx_v3 = 0; // v3 vertex block index
  31291. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  31292. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  31293. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  31294. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  31295. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  31296. subSq = options.subDiv.max * options.subDiv.max;
  31297. options.facetPartitioning.length = 0;
  31298. }
  31299. // reset the normals
  31300. for (index = 0; index < positions.length; index++) {
  31301. normals[index] = 0.0;
  31302. }
  31303. // Loop : 1 indice triplet = 1 facet
  31304. var nbFaces = (indices.length / 3) | 0;
  31305. for (index = 0; index < nbFaces; index++) {
  31306. // get the indexes of the coordinates of each vertex of the facet
  31307. v1x = indices[index * 3] * 3;
  31308. v1y = v1x + 1;
  31309. v1z = v1x + 2;
  31310. v2x = indices[index * 3 + 1] * 3;
  31311. v2y = v2x + 1;
  31312. v2z = v2x + 2;
  31313. v3x = indices[index * 3 + 2] * 3;
  31314. v3y = v3x + 1;
  31315. v3z = v3x + 2;
  31316. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  31317. p1p2y = positions[v1y] - positions[v2y];
  31318. p1p2z = positions[v1z] - positions[v2z];
  31319. p3p2x = positions[v3x] - positions[v2x];
  31320. p3p2y = positions[v3y] - positions[v2y];
  31321. p3p2z = positions[v3z] - positions[v2z];
  31322. // compute the face normal with the cross product
  31323. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  31324. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  31325. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  31326. // normalize this normal and store it in the array facetData
  31327. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31328. length = (length === 0) ? 1.0 : length;
  31329. faceNormalx /= length;
  31330. faceNormaly /= length;
  31331. faceNormalz /= length;
  31332. if (computeFacetNormals && options) {
  31333. options.facetNormals[index].x = faceNormalx;
  31334. options.facetNormals[index].y = faceNormaly;
  31335. options.facetNormals[index].z = faceNormalz;
  31336. }
  31337. if (computeFacetPositions && options) {
  31338. // compute and the facet barycenter coordinates in the array facetPositions
  31339. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  31340. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  31341. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  31342. }
  31343. if (computeFacetPartitioning && options) {
  31344. // store the facet indexes in arrays in the main facetPartitioning array :
  31345. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  31346. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  31347. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  31348. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  31349. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31350. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31351. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31352. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31353. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31354. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31355. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31356. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31357. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31358. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  31359. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  31360. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  31361. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  31362. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  31363. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  31364. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  31365. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  31366. // push each facet index in each block containing the vertex
  31367. options.facetPartitioning[block_idx_v1].push(index);
  31368. if (block_idx_v2 != block_idx_v1) {
  31369. options.facetPartitioning[block_idx_v2].push(index);
  31370. }
  31371. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  31372. options.facetPartitioning[block_idx_v3].push(index);
  31373. }
  31374. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  31375. options.facetPartitioning[block_idx_o].push(index);
  31376. }
  31377. }
  31378. if (computeDepthSort && options && options.facetPositions) {
  31379. var dsf = depthSortedFacets[index];
  31380. dsf.ind = index * 3;
  31381. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  31382. }
  31383. // compute the normals anyway
  31384. normals[v1x] += faceNormalx; // accumulate all the normals per face
  31385. normals[v1y] += faceNormaly;
  31386. normals[v1z] += faceNormalz;
  31387. normals[v2x] += faceNormalx;
  31388. normals[v2y] += faceNormaly;
  31389. normals[v2z] += faceNormalz;
  31390. normals[v3x] += faceNormalx;
  31391. normals[v3y] += faceNormaly;
  31392. normals[v3z] += faceNormalz;
  31393. }
  31394. // last normalization of each normal
  31395. for (index = 0; index < normals.length / 3; index++) {
  31396. faceNormalx = normals[index * 3];
  31397. faceNormaly = normals[index * 3 + 1];
  31398. faceNormalz = normals[index * 3 + 2];
  31399. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31400. length = (length === 0) ? 1.0 : length;
  31401. faceNormalx /= length;
  31402. faceNormaly /= length;
  31403. faceNormalz /= length;
  31404. normals[index * 3] = faceNormalx;
  31405. normals[index * 3 + 1] = faceNormaly;
  31406. normals[index * 3 + 2] = faceNormalz;
  31407. }
  31408. };
  31409. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  31410. var li = indices.length;
  31411. var ln = normals.length;
  31412. var i;
  31413. var n;
  31414. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31415. switch (sideOrientation) {
  31416. case BABYLON.Mesh.FRONTSIDE:
  31417. // nothing changed
  31418. break;
  31419. case BABYLON.Mesh.BACKSIDE:
  31420. var tmp;
  31421. // indices
  31422. for (i = 0; i < li; i += 3) {
  31423. tmp = indices[i];
  31424. indices[i] = indices[i + 2];
  31425. indices[i + 2] = tmp;
  31426. }
  31427. // normals
  31428. for (n = 0; n < ln; n++) {
  31429. normals[n] = -normals[n];
  31430. }
  31431. break;
  31432. case BABYLON.Mesh.DOUBLESIDE:
  31433. // positions
  31434. var lp = positions.length;
  31435. var l = lp / 3;
  31436. for (var p = 0; p < lp; p++) {
  31437. positions[lp + p] = positions[p];
  31438. }
  31439. // indices
  31440. for (i = 0; i < li; i += 3) {
  31441. indices[i + li] = indices[i + 2] + l;
  31442. indices[i + 1 + li] = indices[i + 1] + l;
  31443. indices[i + 2 + li] = indices[i] + l;
  31444. }
  31445. // normals
  31446. for (n = 0; n < ln; n++) {
  31447. normals[ln + n] = -normals[n];
  31448. }
  31449. // uvs
  31450. var lu = uvs.length;
  31451. var u = 0;
  31452. for (u = 0; u < lu; u++) {
  31453. uvs[u + lu] = uvs[u];
  31454. }
  31455. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31456. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31457. u = 0;
  31458. for (i = 0; i < lu / 2; i++) {
  31459. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  31460. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  31461. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  31462. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  31463. u += 2;
  31464. }
  31465. break;
  31466. }
  31467. };
  31468. /**
  31469. * Creates a new VertexData from the imported parameters.
  31470. */
  31471. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31472. var vertexData = new VertexData();
  31473. // positions
  31474. var positions = parsedVertexData.positions;
  31475. if (positions) {
  31476. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31477. }
  31478. // normals
  31479. var normals = parsedVertexData.normals;
  31480. if (normals) {
  31481. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31482. }
  31483. // tangents
  31484. var tangents = parsedVertexData.tangents;
  31485. if (tangents) {
  31486. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  31487. }
  31488. // uvs
  31489. var uvs = parsedVertexData.uvs;
  31490. if (uvs) {
  31491. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31492. }
  31493. // uv2s
  31494. var uv2s = parsedVertexData.uv2s;
  31495. if (uv2s) {
  31496. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31497. }
  31498. // uv3s
  31499. var uv3s = parsedVertexData.uv3s;
  31500. if (uv3s) {
  31501. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31502. }
  31503. // uv4s
  31504. var uv4s = parsedVertexData.uv4s;
  31505. if (uv4s) {
  31506. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31507. }
  31508. // uv5s
  31509. var uv5s = parsedVertexData.uv5s;
  31510. if (uv5s) {
  31511. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31512. }
  31513. // uv6s
  31514. var uv6s = parsedVertexData.uv6s;
  31515. if (uv6s) {
  31516. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31517. }
  31518. // colors
  31519. var colors = parsedVertexData.colors;
  31520. if (colors) {
  31521. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31522. }
  31523. // matricesIndices
  31524. var matricesIndices = parsedVertexData.matricesIndices;
  31525. if (matricesIndices) {
  31526. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31527. }
  31528. // matricesWeights
  31529. var matricesWeights = parsedVertexData.matricesWeights;
  31530. if (matricesWeights) {
  31531. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31532. }
  31533. // indices
  31534. var indices = parsedVertexData.indices;
  31535. if (indices) {
  31536. vertexData.indices = indices;
  31537. }
  31538. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31539. };
  31540. return VertexData;
  31541. }());
  31542. BABYLON.VertexData = VertexData;
  31543. })(BABYLON || (BABYLON = {}));
  31544. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  31545. var BABYLON;
  31546. (function (BABYLON) {
  31547. var Geometry = /** @class */ (function () {
  31548. function Geometry(id, scene, vertexData, updatable, mesh) {
  31549. if (updatable === void 0) { updatable = false; }
  31550. if (mesh === void 0) { mesh = null; }
  31551. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31552. this._totalVertices = 0;
  31553. this._isDisposed = false;
  31554. this._indexBufferIsUpdatable = false;
  31555. this.id = id;
  31556. this._engine = scene.getEngine();
  31557. this._meshes = [];
  31558. this._scene = scene;
  31559. //Init vertex buffer cache
  31560. this._vertexBuffers = {};
  31561. this._indices = [];
  31562. this._updatable = updatable;
  31563. // vertexData
  31564. if (vertexData) {
  31565. this.setAllVerticesData(vertexData, updatable);
  31566. }
  31567. else {
  31568. this._totalVertices = 0;
  31569. this._indices = [];
  31570. }
  31571. if (this._engine.getCaps().vertexArrayObject) {
  31572. this._vertexArrayObjects = {};
  31573. }
  31574. // applyToMesh
  31575. if (mesh) {
  31576. if (mesh.getClassName() === "LinesMesh") {
  31577. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31578. this.updateExtend();
  31579. }
  31580. this.applyToMesh(mesh);
  31581. mesh.computeWorldMatrix(true);
  31582. }
  31583. }
  31584. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31585. /**
  31586. * 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
  31587. * @returns The Bias Vector
  31588. */
  31589. get: function () {
  31590. return this._boundingBias;
  31591. },
  31592. set: function (value) {
  31593. if (this._boundingBias && this._boundingBias.equals(value)) {
  31594. return;
  31595. }
  31596. this._boundingBias = value.clone();
  31597. this.updateBoundingInfo(true, null);
  31598. },
  31599. enumerable: true,
  31600. configurable: true
  31601. });
  31602. Geometry.CreateGeometryForMesh = function (mesh) {
  31603. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  31604. geometry.applyToMesh(mesh);
  31605. return geometry;
  31606. };
  31607. Object.defineProperty(Geometry.prototype, "extend", {
  31608. get: function () {
  31609. return this._extend;
  31610. },
  31611. enumerable: true,
  31612. configurable: true
  31613. });
  31614. Geometry.prototype.getScene = function () {
  31615. return this._scene;
  31616. };
  31617. Geometry.prototype.getEngine = function () {
  31618. return this._engine;
  31619. };
  31620. Geometry.prototype.isReady = function () {
  31621. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31622. };
  31623. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  31624. get: function () {
  31625. for (var index = 0; index < this._meshes.length; index++) {
  31626. if (!this._meshes[index].doNotSerialize) {
  31627. return false;
  31628. }
  31629. }
  31630. return true;
  31631. },
  31632. enumerable: true,
  31633. configurable: true
  31634. });
  31635. Geometry.prototype._rebuild = function () {
  31636. if (this._vertexArrayObjects) {
  31637. this._vertexArrayObjects = {};
  31638. }
  31639. // Index buffer
  31640. if (this._meshes.length !== 0 && this._indices) {
  31641. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31642. }
  31643. // Vertex buffers
  31644. for (var key in this._vertexBuffers) {
  31645. var vertexBuffer = this._vertexBuffers[key];
  31646. vertexBuffer._rebuild();
  31647. }
  31648. };
  31649. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31650. vertexData.applyToGeometry(this, updatable);
  31651. this.notifyUpdate();
  31652. };
  31653. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31654. if (updatable === void 0) { updatable = false; }
  31655. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31656. this.setVerticesBuffer(buffer);
  31657. };
  31658. Geometry.prototype.removeVerticesData = function (kind) {
  31659. if (this._vertexBuffers[kind]) {
  31660. this._vertexBuffers[kind].dispose();
  31661. delete this._vertexBuffers[kind];
  31662. }
  31663. };
  31664. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31665. var kind = buffer.getKind();
  31666. if (this._vertexBuffers[kind]) {
  31667. this._vertexBuffers[kind].dispose();
  31668. }
  31669. this._vertexBuffers[kind] = buffer;
  31670. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31671. var data = buffer.getData();
  31672. var stride = buffer.getStrideSize();
  31673. this._totalVertices = data.length / stride;
  31674. this.updateExtend(data, stride);
  31675. this._resetPointsArrayCache();
  31676. var meshes = this._meshes;
  31677. var numOfMeshes = meshes.length;
  31678. for (var index = 0; index < numOfMeshes; index++) {
  31679. var mesh = meshes[index];
  31680. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31681. mesh._createGlobalSubMesh(false);
  31682. mesh.computeWorldMatrix(true);
  31683. }
  31684. }
  31685. this.notifyUpdate(kind);
  31686. if (this._vertexArrayObjects) {
  31687. this._disposeVertexArrayObjects();
  31688. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31689. }
  31690. };
  31691. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31692. var vertexBuffer = this.getVertexBuffer(kind);
  31693. if (!vertexBuffer) {
  31694. return;
  31695. }
  31696. vertexBuffer.updateDirectly(data, offset);
  31697. this.notifyUpdate(kind);
  31698. };
  31699. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31700. if (updateExtends === void 0) { updateExtends = false; }
  31701. var vertexBuffer = this.getVertexBuffer(kind);
  31702. if (!vertexBuffer) {
  31703. return;
  31704. }
  31705. vertexBuffer.update(data);
  31706. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31707. var stride = vertexBuffer.getStrideSize();
  31708. this._totalVertices = data.length / stride;
  31709. this.updateBoundingInfo(updateExtends, data);
  31710. }
  31711. this.notifyUpdate(kind);
  31712. };
  31713. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31714. if (updateExtends) {
  31715. this.updateExtend(data);
  31716. }
  31717. var meshes = this._meshes;
  31718. var numOfMeshes = meshes.length;
  31719. this._resetPointsArrayCache();
  31720. for (var index = 0; index < numOfMeshes; index++) {
  31721. var mesh = meshes[index];
  31722. if (updateExtends) {
  31723. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31724. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31725. var subMesh = mesh.subMeshes[subIndex];
  31726. subMesh.refreshBoundingInfo();
  31727. }
  31728. }
  31729. }
  31730. };
  31731. Geometry.prototype._bind = function (effect, indexToBind) {
  31732. if (!effect) {
  31733. return;
  31734. }
  31735. if (indexToBind === undefined) {
  31736. indexToBind = this._indexBuffer;
  31737. }
  31738. var vbs = this.getVertexBuffers();
  31739. if (!vbs) {
  31740. return;
  31741. }
  31742. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31743. this._engine.bindBuffers(vbs, indexToBind, effect);
  31744. return;
  31745. }
  31746. // Using VAO
  31747. if (!this._vertexArrayObjects[effect.key]) {
  31748. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31749. }
  31750. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31751. };
  31752. Geometry.prototype.getTotalVertices = function () {
  31753. if (!this.isReady()) {
  31754. return 0;
  31755. }
  31756. return this._totalVertices;
  31757. };
  31758. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31759. var vertexBuffer = this.getVertexBuffer(kind);
  31760. if (!vertexBuffer) {
  31761. return null;
  31762. }
  31763. var orig = vertexBuffer.getData();
  31764. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31765. return orig;
  31766. }
  31767. else {
  31768. var len = orig.length;
  31769. var copy = [];
  31770. for (var i = 0; i < len; i++) {
  31771. copy.push(orig[i]);
  31772. }
  31773. return copy;
  31774. }
  31775. };
  31776. /**
  31777. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31778. * Possible `kind` values :
  31779. * - BABYLON.VertexBuffer.PositionKind
  31780. * - BABYLON.VertexBuffer.UVKind
  31781. * - BABYLON.VertexBuffer.UV2Kind
  31782. * - BABYLON.VertexBuffer.UV3Kind
  31783. * - BABYLON.VertexBuffer.UV4Kind
  31784. * - BABYLON.VertexBuffer.UV5Kind
  31785. * - BABYLON.VertexBuffer.UV6Kind
  31786. * - BABYLON.VertexBuffer.ColorKind
  31787. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31788. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31789. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31790. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31791. */
  31792. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31793. var vb = this._vertexBuffers[kind];
  31794. if (!vb) {
  31795. return false;
  31796. }
  31797. return vb.isUpdatable();
  31798. };
  31799. Geometry.prototype.getVertexBuffer = function (kind) {
  31800. if (!this.isReady()) {
  31801. return null;
  31802. }
  31803. return this._vertexBuffers[kind];
  31804. };
  31805. Geometry.prototype.getVertexBuffers = function () {
  31806. if (!this.isReady()) {
  31807. return null;
  31808. }
  31809. return this._vertexBuffers;
  31810. };
  31811. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31812. if (!this._vertexBuffers) {
  31813. if (this._delayInfo) {
  31814. return this._delayInfo.indexOf(kind) !== -1;
  31815. }
  31816. return false;
  31817. }
  31818. return this._vertexBuffers[kind] !== undefined;
  31819. };
  31820. Geometry.prototype.getVerticesDataKinds = function () {
  31821. var result = [];
  31822. var kind;
  31823. if (!this._vertexBuffers && this._delayInfo) {
  31824. for (kind in this._delayInfo) {
  31825. result.push(kind);
  31826. }
  31827. }
  31828. else {
  31829. for (kind in this._vertexBuffers) {
  31830. result.push(kind);
  31831. }
  31832. }
  31833. return result;
  31834. };
  31835. Geometry.prototype.updateIndices = function (indices, offset) {
  31836. if (!this._indexBuffer) {
  31837. return;
  31838. }
  31839. if (!this._indexBufferIsUpdatable) {
  31840. this.setIndices(indices, null, true);
  31841. }
  31842. else {
  31843. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31844. }
  31845. };
  31846. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31847. if (totalVertices === void 0) { totalVertices = null; }
  31848. if (updatable === void 0) { updatable = false; }
  31849. if (this._indexBuffer) {
  31850. this._engine._releaseBuffer(this._indexBuffer);
  31851. }
  31852. this._disposeVertexArrayObjects();
  31853. this._indices = indices;
  31854. this._indexBufferIsUpdatable = updatable;
  31855. if (this._meshes.length !== 0 && this._indices) {
  31856. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31857. }
  31858. if (totalVertices != undefined) {
  31859. this._totalVertices = totalVertices;
  31860. }
  31861. var meshes = this._meshes;
  31862. var numOfMeshes = meshes.length;
  31863. for (var index = 0; index < numOfMeshes; index++) {
  31864. meshes[index]._createGlobalSubMesh(true);
  31865. }
  31866. this.notifyUpdate();
  31867. };
  31868. Geometry.prototype.getTotalIndices = function () {
  31869. if (!this.isReady()) {
  31870. return 0;
  31871. }
  31872. return this._indices.length;
  31873. };
  31874. Geometry.prototype.getIndices = function (copyWhenShared) {
  31875. if (!this.isReady()) {
  31876. return null;
  31877. }
  31878. var orig = this._indices;
  31879. if (!copyWhenShared || this._meshes.length === 1) {
  31880. return orig;
  31881. }
  31882. else {
  31883. var len = orig.length;
  31884. var copy = [];
  31885. for (var i = 0; i < len; i++) {
  31886. copy.push(orig[i]);
  31887. }
  31888. return copy;
  31889. }
  31890. };
  31891. Geometry.prototype.getIndexBuffer = function () {
  31892. if (!this.isReady()) {
  31893. return null;
  31894. }
  31895. return this._indexBuffer;
  31896. };
  31897. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31898. if (effect === void 0) { effect = null; }
  31899. if (!effect || !this._vertexArrayObjects) {
  31900. return;
  31901. }
  31902. if (this._vertexArrayObjects[effect.key]) {
  31903. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31904. delete this._vertexArrayObjects[effect.key];
  31905. }
  31906. };
  31907. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31908. var meshes = this._meshes;
  31909. var index = meshes.indexOf(mesh);
  31910. if (index === -1) {
  31911. return;
  31912. }
  31913. meshes.splice(index, 1);
  31914. mesh._geometry = null;
  31915. if (meshes.length === 0 && shouldDispose) {
  31916. this.dispose();
  31917. }
  31918. };
  31919. Geometry.prototype.applyToMesh = function (mesh) {
  31920. if (mesh._geometry === this) {
  31921. return;
  31922. }
  31923. var previousGeometry = mesh._geometry;
  31924. if (previousGeometry) {
  31925. previousGeometry.releaseForMesh(mesh);
  31926. }
  31927. var meshes = this._meshes;
  31928. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31929. mesh._geometry = this;
  31930. this._scene.pushGeometry(this);
  31931. meshes.push(mesh);
  31932. if (this.isReady()) {
  31933. this._applyToMesh(mesh);
  31934. }
  31935. else {
  31936. mesh._boundingInfo = this._boundingInfo;
  31937. }
  31938. };
  31939. Geometry.prototype.updateExtend = function (data, stride) {
  31940. if (data === void 0) { data = null; }
  31941. if (!data) {
  31942. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31943. }
  31944. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31945. };
  31946. Geometry.prototype._applyToMesh = function (mesh) {
  31947. var numOfMeshes = this._meshes.length;
  31948. // vertexBuffers
  31949. for (var kind in this._vertexBuffers) {
  31950. if (numOfMeshes === 1) {
  31951. this._vertexBuffers[kind].create();
  31952. }
  31953. var buffer = this._vertexBuffers[kind].getBuffer();
  31954. if (buffer)
  31955. buffer.references = numOfMeshes;
  31956. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31957. if (!this._extend) {
  31958. this.updateExtend(this._vertexBuffers[kind].getData());
  31959. }
  31960. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31961. mesh._createGlobalSubMesh(false);
  31962. //bounding info was just created again, world matrix should be applied again.
  31963. mesh._updateBoundingInfo();
  31964. }
  31965. }
  31966. // indexBuffer
  31967. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31968. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31969. }
  31970. if (this._indexBuffer) {
  31971. this._indexBuffer.references = numOfMeshes;
  31972. }
  31973. };
  31974. Geometry.prototype.notifyUpdate = function (kind) {
  31975. if (this.onGeometryUpdated) {
  31976. this.onGeometryUpdated(this, kind);
  31977. }
  31978. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31979. var mesh = _a[_i];
  31980. mesh._markSubMeshesAsAttributesDirty();
  31981. }
  31982. };
  31983. Geometry.prototype.load = function (scene, onLoaded) {
  31984. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31985. return;
  31986. }
  31987. if (this.isReady()) {
  31988. if (onLoaded) {
  31989. onLoaded();
  31990. }
  31991. return;
  31992. }
  31993. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31994. this._queueLoad(scene, onLoaded);
  31995. };
  31996. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31997. var _this = this;
  31998. if (!this.delayLoadingFile) {
  31999. return;
  32000. }
  32001. scene._addPendingData(this);
  32002. scene._loadFile(this.delayLoadingFile, function (data) {
  32003. if (!_this._delayLoadingFunction) {
  32004. return;
  32005. }
  32006. _this._delayLoadingFunction(JSON.parse(data), _this);
  32007. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32008. _this._delayInfo = [];
  32009. scene._removePendingData(_this);
  32010. var meshes = _this._meshes;
  32011. var numOfMeshes = meshes.length;
  32012. for (var index = 0; index < numOfMeshes; index++) {
  32013. _this._applyToMesh(meshes[index]);
  32014. }
  32015. if (onLoaded) {
  32016. onLoaded();
  32017. }
  32018. }, undefined, true);
  32019. };
  32020. /**
  32021. * Invert the geometry to move from a right handed system to a left handed one.
  32022. */
  32023. Geometry.prototype.toLeftHanded = function () {
  32024. // Flip faces
  32025. var tIndices = this.getIndices(false);
  32026. if (tIndices != null && tIndices.length > 0) {
  32027. for (var i = 0; i < tIndices.length; i += 3) {
  32028. var tTemp = tIndices[i + 0];
  32029. tIndices[i + 0] = tIndices[i + 2];
  32030. tIndices[i + 2] = tTemp;
  32031. }
  32032. this.setIndices(tIndices);
  32033. }
  32034. // Negate position.z
  32035. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  32036. if (tPositions != null && tPositions.length > 0) {
  32037. for (var i = 0; i < tPositions.length; i += 3) {
  32038. tPositions[i + 2] = -tPositions[i + 2];
  32039. }
  32040. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  32041. }
  32042. // Negate normal.z
  32043. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  32044. if (tNormals != null && tNormals.length > 0) {
  32045. for (var i = 0; i < tNormals.length; i += 3) {
  32046. tNormals[i + 2] = -tNormals[i + 2];
  32047. }
  32048. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  32049. }
  32050. };
  32051. // Cache
  32052. Geometry.prototype._resetPointsArrayCache = function () {
  32053. this._positions = null;
  32054. };
  32055. Geometry.prototype._generatePointsArray = function () {
  32056. if (this._positions)
  32057. return true;
  32058. this._positions = [];
  32059. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32060. if (!data) {
  32061. return false;
  32062. }
  32063. for (var index = 0; index < data.length; index += 3) {
  32064. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  32065. }
  32066. return true;
  32067. };
  32068. Geometry.prototype.isDisposed = function () {
  32069. return this._isDisposed;
  32070. };
  32071. Geometry.prototype._disposeVertexArrayObjects = function () {
  32072. if (this._vertexArrayObjects) {
  32073. for (var kind in this._vertexArrayObjects) {
  32074. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  32075. }
  32076. this._vertexArrayObjects = {};
  32077. }
  32078. };
  32079. Geometry.prototype.dispose = function () {
  32080. var meshes = this._meshes;
  32081. var numOfMeshes = meshes.length;
  32082. var index;
  32083. for (index = 0; index < numOfMeshes; index++) {
  32084. this.releaseForMesh(meshes[index]);
  32085. }
  32086. this._meshes = [];
  32087. this._disposeVertexArrayObjects();
  32088. for (var kind in this._vertexBuffers) {
  32089. this._vertexBuffers[kind].dispose();
  32090. }
  32091. this._vertexBuffers = {};
  32092. this._totalVertices = 0;
  32093. if (this._indexBuffer) {
  32094. this._engine._releaseBuffer(this._indexBuffer);
  32095. }
  32096. this._indexBuffer = null;
  32097. this._indices = [];
  32098. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32099. this.delayLoadingFile = null;
  32100. this._delayLoadingFunction = null;
  32101. this._delayInfo = [];
  32102. this._boundingInfo = null;
  32103. this._scene.removeGeometry(this);
  32104. this._isDisposed = true;
  32105. };
  32106. Geometry.prototype.copy = function (id) {
  32107. var vertexData = new BABYLON.VertexData();
  32108. vertexData.indices = [];
  32109. var indices = this.getIndices();
  32110. if (indices) {
  32111. for (var index = 0; index < indices.length; index++) {
  32112. vertexData.indices.push(indices[index]);
  32113. }
  32114. }
  32115. var updatable = false;
  32116. var stopChecking = false;
  32117. var kind;
  32118. for (kind in this._vertexBuffers) {
  32119. // using slice() to make a copy of the array and not just reference it
  32120. var data = this.getVerticesData(kind);
  32121. if (data instanceof Float32Array) {
  32122. vertexData.set(new Float32Array(data), kind);
  32123. }
  32124. else {
  32125. vertexData.set(data.slice(0), kind);
  32126. }
  32127. if (!stopChecking) {
  32128. var vb = this.getVertexBuffer(kind);
  32129. if (vb) {
  32130. updatable = vb.isUpdatable();
  32131. stopChecking = !updatable;
  32132. }
  32133. }
  32134. }
  32135. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  32136. geometry.delayLoadState = this.delayLoadState;
  32137. geometry.delayLoadingFile = this.delayLoadingFile;
  32138. geometry._delayLoadingFunction = this._delayLoadingFunction;
  32139. for (kind in this._delayInfo) {
  32140. geometry._delayInfo = geometry._delayInfo || [];
  32141. geometry._delayInfo.push(kind);
  32142. }
  32143. // Bounding info
  32144. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32145. return geometry;
  32146. };
  32147. Geometry.prototype.serialize = function () {
  32148. var serializationObject = {};
  32149. serializationObject.id = this.id;
  32150. serializationObject.updatable = this._updatable;
  32151. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32152. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32153. }
  32154. return serializationObject;
  32155. };
  32156. Geometry.prototype.toNumberArray = function (origin) {
  32157. if (Array.isArray(origin)) {
  32158. return origin;
  32159. }
  32160. else {
  32161. return Array.prototype.slice.call(origin);
  32162. }
  32163. };
  32164. Geometry.prototype.serializeVerticeData = function () {
  32165. var serializationObject = this.serialize();
  32166. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32167. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  32168. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  32169. serializationObject.positions._updatable = true;
  32170. }
  32171. }
  32172. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32173. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  32174. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  32175. serializationObject.normals._updatable = true;
  32176. }
  32177. }
  32178. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32179. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  32180. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  32181. serializationObject.uvs._updatable = true;
  32182. }
  32183. }
  32184. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32185. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  32186. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  32187. serializationObject.uv2s._updatable = true;
  32188. }
  32189. }
  32190. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32191. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  32192. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  32193. serializationObject.uv3s._updatable = true;
  32194. }
  32195. }
  32196. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32197. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  32198. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  32199. serializationObject.uv4s._updatable = true;
  32200. }
  32201. }
  32202. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32203. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  32204. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  32205. serializationObject.uv5s._updatable = true;
  32206. }
  32207. }
  32208. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32209. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  32210. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  32211. serializationObject.uv6s._updatable = true;
  32212. }
  32213. }
  32214. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32215. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  32216. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  32217. serializationObject.colors._updatable = true;
  32218. }
  32219. }
  32220. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32221. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  32222. serializationObject.matricesIndices._isExpanded = true;
  32223. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32224. serializationObject.matricesIndices._updatable = true;
  32225. }
  32226. }
  32227. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32228. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  32229. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32230. serializationObject.matricesWeights._updatable = true;
  32231. }
  32232. }
  32233. serializationObject.indices = this.toNumberArray(this.getIndices());
  32234. return serializationObject;
  32235. };
  32236. // Statics
  32237. Geometry.ExtractFromMesh = function (mesh, id) {
  32238. var geometry = mesh._geometry;
  32239. if (!geometry) {
  32240. return null;
  32241. }
  32242. return geometry.copy(id);
  32243. };
  32244. /**
  32245. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  32246. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  32247. * Be aware Math.random() could cause collisions, but:
  32248. * "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"
  32249. */
  32250. Geometry.RandomId = function () {
  32251. return BABYLON.Tools.RandomId();
  32252. };
  32253. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  32254. var scene = mesh.getScene();
  32255. // Geometry
  32256. var geometryId = parsedGeometry.geometryId;
  32257. if (geometryId) {
  32258. var geometry = scene.getGeometryByID(geometryId);
  32259. if (geometry) {
  32260. geometry.applyToMesh(mesh);
  32261. }
  32262. }
  32263. else if (parsedGeometry instanceof ArrayBuffer) {
  32264. var binaryInfo = mesh._binaryInfo;
  32265. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  32266. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  32267. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  32268. }
  32269. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  32270. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  32271. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  32272. }
  32273. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  32274. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  32275. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  32276. }
  32277. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  32278. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  32279. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  32280. }
  32281. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  32282. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  32283. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  32284. }
  32285. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  32286. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  32287. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  32288. }
  32289. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  32290. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  32291. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  32292. }
  32293. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  32294. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  32295. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  32296. }
  32297. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  32298. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  32299. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  32300. }
  32301. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  32302. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  32303. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  32304. }
  32305. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  32306. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  32307. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  32308. }
  32309. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  32310. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  32311. mesh.setIndices(indicesData, null);
  32312. }
  32313. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  32314. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  32315. mesh.subMeshes = [];
  32316. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  32317. var materialIndex = subMeshesData[(i * 5) + 0];
  32318. var verticesStart = subMeshesData[(i * 5) + 1];
  32319. var verticesCount = subMeshesData[(i * 5) + 2];
  32320. var indexStart = subMeshesData[(i * 5) + 3];
  32321. var indexCount = subMeshesData[(i * 5) + 4];
  32322. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  32323. }
  32324. }
  32325. }
  32326. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  32327. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  32328. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  32329. if (parsedGeometry.uvs) {
  32330. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  32331. }
  32332. if (parsedGeometry.uvs2) {
  32333. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  32334. }
  32335. if (parsedGeometry.uvs3) {
  32336. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  32337. }
  32338. if (parsedGeometry.uvs4) {
  32339. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  32340. }
  32341. if (parsedGeometry.uvs5) {
  32342. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  32343. }
  32344. if (parsedGeometry.uvs6) {
  32345. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  32346. }
  32347. if (parsedGeometry.colors) {
  32348. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  32349. }
  32350. if (parsedGeometry.matricesIndices) {
  32351. if (!parsedGeometry.matricesIndices._isExpanded) {
  32352. var floatIndices = [];
  32353. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32354. var matricesIndex = parsedGeometry.matricesIndices[i];
  32355. floatIndices.push(matricesIndex & 0x000000FF);
  32356. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32357. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32358. floatIndices.push(matricesIndex >> 24);
  32359. }
  32360. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  32361. }
  32362. else {
  32363. delete parsedGeometry.matricesIndices._isExpanded;
  32364. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  32365. }
  32366. }
  32367. if (parsedGeometry.matricesIndicesExtra) {
  32368. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32369. var floatIndices = [];
  32370. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32371. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32372. floatIndices.push(matricesIndex & 0x000000FF);
  32373. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32374. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32375. floatIndices.push(matricesIndex >> 24);
  32376. }
  32377. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  32378. }
  32379. else {
  32380. delete parsedGeometry.matricesIndices._isExpanded;
  32381. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  32382. }
  32383. }
  32384. if (parsedGeometry.matricesWeights) {
  32385. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  32386. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  32387. }
  32388. if (parsedGeometry.matricesWeightsExtra) {
  32389. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  32390. }
  32391. mesh.setIndices(parsedGeometry.indices, null);
  32392. }
  32393. // SubMeshes
  32394. if (parsedGeometry.subMeshes) {
  32395. mesh.subMeshes = [];
  32396. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32397. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32398. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32399. }
  32400. }
  32401. // Flat shading
  32402. if (mesh._shouldGenerateFlatShading) {
  32403. mesh.convertToFlatShadedMesh();
  32404. delete mesh._shouldGenerateFlatShading;
  32405. }
  32406. // Update
  32407. mesh.computeWorldMatrix(true);
  32408. // Octree
  32409. var sceneOctree = scene.selectionOctree;
  32410. if (sceneOctree !== undefined && sceneOctree !== null) {
  32411. sceneOctree.addMesh(mesh);
  32412. }
  32413. };
  32414. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  32415. var epsilon = 1e-3;
  32416. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  32417. return;
  32418. }
  32419. var noInfluenceBoneIndex = 0.0;
  32420. if (parsedGeometry.skeletonId > -1) {
  32421. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  32422. if (!skeleton) {
  32423. return;
  32424. }
  32425. noInfluenceBoneIndex = skeleton.bones.length;
  32426. }
  32427. else {
  32428. return;
  32429. }
  32430. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32431. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32432. var matricesWeights = parsedGeometry.matricesWeights;
  32433. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  32434. var influencers = parsedGeometry.numBoneInfluencer;
  32435. var size = matricesWeights.length;
  32436. for (var i = 0; i < size; i += 4) {
  32437. var weight = 0.0;
  32438. var firstZeroWeight = -1;
  32439. for (var j = 0; j < 4; j++) {
  32440. var w = matricesWeights[i + j];
  32441. weight += w;
  32442. if (w < epsilon && firstZeroWeight < 0) {
  32443. firstZeroWeight = j;
  32444. }
  32445. }
  32446. if (matricesWeightsExtra) {
  32447. for (var j = 0; j < 4; j++) {
  32448. var w = matricesWeightsExtra[i + j];
  32449. weight += w;
  32450. if (w < epsilon && firstZeroWeight < 0) {
  32451. firstZeroWeight = j + 4;
  32452. }
  32453. }
  32454. }
  32455. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32456. firstZeroWeight = influencers - 1;
  32457. }
  32458. if (weight > epsilon) {
  32459. var mweight = 1.0 / weight;
  32460. for (var j = 0; j < 4; j++) {
  32461. matricesWeights[i + j] *= mweight;
  32462. }
  32463. if (matricesWeightsExtra) {
  32464. for (var j = 0; j < 4; j++) {
  32465. matricesWeightsExtra[i + j] *= mweight;
  32466. }
  32467. }
  32468. }
  32469. else {
  32470. if (firstZeroWeight >= 4) {
  32471. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32472. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32473. }
  32474. else {
  32475. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32476. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32477. }
  32478. }
  32479. }
  32480. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32481. if (parsedGeometry.matricesWeightsExtra) {
  32482. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32483. }
  32484. };
  32485. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32486. if (scene.getGeometryByID(parsedVertexData.id)) {
  32487. return null; // null since geometry could be something else than a box...
  32488. }
  32489. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  32490. if (BABYLON.Tags) {
  32491. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32492. }
  32493. if (parsedVertexData.delayLoadingFile) {
  32494. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32495. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32496. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32497. geometry._delayInfo = [];
  32498. if (parsedVertexData.hasUVs) {
  32499. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32500. }
  32501. if (parsedVertexData.hasUVs2) {
  32502. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32503. }
  32504. if (parsedVertexData.hasUVs3) {
  32505. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32506. }
  32507. if (parsedVertexData.hasUVs4) {
  32508. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32509. }
  32510. if (parsedVertexData.hasUVs5) {
  32511. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32512. }
  32513. if (parsedVertexData.hasUVs6) {
  32514. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32515. }
  32516. if (parsedVertexData.hasColors) {
  32517. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32518. }
  32519. if (parsedVertexData.hasMatricesIndices) {
  32520. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32521. }
  32522. if (parsedVertexData.hasMatricesWeights) {
  32523. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32524. }
  32525. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32526. }
  32527. else {
  32528. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32529. }
  32530. scene.pushGeometry(geometry, true);
  32531. return geometry;
  32532. };
  32533. return Geometry;
  32534. }());
  32535. BABYLON.Geometry = Geometry;
  32536. /////// Primitives //////////////////////////////////////////////
  32537. //export module Geometry.Primitives {
  32538. /// Abstract class
  32539. var _PrimitiveGeometry = /** @class */ (function (_super) {
  32540. __extends(_PrimitiveGeometry, _super);
  32541. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  32542. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  32543. if (mesh === void 0) { mesh = null; }
  32544. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  32545. _this._canBeRegenerated = _canBeRegenerated;
  32546. _this._beingRegenerated = true;
  32547. _this.regenerate();
  32548. _this._beingRegenerated = false;
  32549. return _this;
  32550. }
  32551. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  32552. return this._canBeRegenerated;
  32553. };
  32554. _PrimitiveGeometry.prototype.regenerate = function () {
  32555. if (!this._canBeRegenerated) {
  32556. return;
  32557. }
  32558. this._beingRegenerated = true;
  32559. this.setAllVerticesData(this._regenerateVertexData(), false);
  32560. this._beingRegenerated = false;
  32561. };
  32562. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  32563. return _super.prototype.copy.call(this, id);
  32564. };
  32565. // overrides
  32566. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32567. if (!this._beingRegenerated) {
  32568. return;
  32569. }
  32570. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32571. };
  32572. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  32573. if (!this._beingRegenerated) {
  32574. return;
  32575. }
  32576. _super.prototype.setVerticesData.call(this, kind, data, false);
  32577. };
  32578. // to override
  32579. // protected
  32580. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  32581. throw new Error("Abstract method");
  32582. };
  32583. _PrimitiveGeometry.prototype.copy = function (id) {
  32584. throw new Error("Must be overriden in sub-classes.");
  32585. };
  32586. _PrimitiveGeometry.prototype.serialize = function () {
  32587. var serializationObject = _super.prototype.serialize.call(this);
  32588. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32589. return serializationObject;
  32590. };
  32591. return _PrimitiveGeometry;
  32592. }(Geometry));
  32593. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  32594. var RibbonGeometry = /** @class */ (function (_super) {
  32595. __extends(RibbonGeometry, _super);
  32596. // Members
  32597. function RibbonGeometry(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32598. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32599. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32600. _this.pathArray = pathArray;
  32601. _this.closeArray = closeArray;
  32602. _this.closePath = closePath;
  32603. _this.offset = offset;
  32604. _this.side = side;
  32605. return _this;
  32606. }
  32607. RibbonGeometry.prototype._regenerateVertexData = function () {
  32608. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32609. };
  32610. RibbonGeometry.prototype.copy = function (id) {
  32611. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  32612. };
  32613. return RibbonGeometry;
  32614. }(_PrimitiveGeometry));
  32615. BABYLON.RibbonGeometry = RibbonGeometry;
  32616. var BoxGeometry = /** @class */ (function (_super) {
  32617. __extends(BoxGeometry, _super);
  32618. // Members
  32619. function BoxGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32620. if (mesh === void 0) { mesh = null; }
  32621. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32622. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32623. _this.size = size;
  32624. _this.side = side;
  32625. return _this;
  32626. }
  32627. BoxGeometry.prototype._regenerateVertexData = function () {
  32628. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32629. };
  32630. BoxGeometry.prototype.copy = function (id) {
  32631. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  32632. };
  32633. BoxGeometry.prototype.serialize = function () {
  32634. var serializationObject = _super.prototype.serialize.call(this);
  32635. serializationObject.size = this.size;
  32636. return serializationObject;
  32637. };
  32638. BoxGeometry.Parse = function (parsedBox, scene) {
  32639. if (scene.getGeometryByID(parsedBox.id)) {
  32640. return null; // null since geometry could be something else than a box...
  32641. }
  32642. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32643. if (BABYLON.Tags) {
  32644. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32645. }
  32646. scene.pushGeometry(box, true);
  32647. return box;
  32648. };
  32649. return BoxGeometry;
  32650. }(_PrimitiveGeometry));
  32651. BABYLON.BoxGeometry = BoxGeometry;
  32652. var SphereGeometry = /** @class */ (function (_super) {
  32653. __extends(SphereGeometry, _super);
  32654. function SphereGeometry(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32655. if (mesh === void 0) { mesh = null; }
  32656. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32657. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32658. _this.segments = segments;
  32659. _this.diameter = diameter;
  32660. _this.side = side;
  32661. return _this;
  32662. }
  32663. SphereGeometry.prototype._regenerateVertexData = function () {
  32664. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32665. };
  32666. SphereGeometry.prototype.copy = function (id) {
  32667. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32668. };
  32669. SphereGeometry.prototype.serialize = function () {
  32670. var serializationObject = _super.prototype.serialize.call(this);
  32671. serializationObject.segments = this.segments;
  32672. serializationObject.diameter = this.diameter;
  32673. return serializationObject;
  32674. };
  32675. SphereGeometry.Parse = function (parsedSphere, scene) {
  32676. if (scene.getGeometryByID(parsedSphere.id)) {
  32677. return null; // null since geometry could be something else than a sphere...
  32678. }
  32679. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32680. if (BABYLON.Tags) {
  32681. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32682. }
  32683. scene.pushGeometry(sphere, true);
  32684. return sphere;
  32685. };
  32686. return SphereGeometry;
  32687. }(_PrimitiveGeometry));
  32688. BABYLON.SphereGeometry = SphereGeometry;
  32689. var DiscGeometry = /** @class */ (function (_super) {
  32690. __extends(DiscGeometry, _super);
  32691. // Members
  32692. function DiscGeometry(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32693. if (mesh === void 0) { mesh = null; }
  32694. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32695. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32696. _this.radius = radius;
  32697. _this.tessellation = tessellation;
  32698. _this.side = side;
  32699. return _this;
  32700. }
  32701. DiscGeometry.prototype._regenerateVertexData = function () {
  32702. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32703. };
  32704. DiscGeometry.prototype.copy = function (id) {
  32705. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32706. };
  32707. return DiscGeometry;
  32708. }(_PrimitiveGeometry));
  32709. BABYLON.DiscGeometry = DiscGeometry;
  32710. var CylinderGeometry = /** @class */ (function (_super) {
  32711. __extends(CylinderGeometry, _super);
  32712. function CylinderGeometry(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32713. if (subdivisions === void 0) { subdivisions = 1; }
  32714. if (mesh === void 0) { mesh = null; }
  32715. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32716. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32717. _this.height = height;
  32718. _this.diameterTop = diameterTop;
  32719. _this.diameterBottom = diameterBottom;
  32720. _this.tessellation = tessellation;
  32721. _this.subdivisions = subdivisions;
  32722. _this.side = side;
  32723. return _this;
  32724. }
  32725. CylinderGeometry.prototype._regenerateVertexData = function () {
  32726. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32727. };
  32728. CylinderGeometry.prototype.copy = function (id) {
  32729. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32730. };
  32731. CylinderGeometry.prototype.serialize = function () {
  32732. var serializationObject = _super.prototype.serialize.call(this);
  32733. serializationObject.height = this.height;
  32734. serializationObject.diameterTop = this.diameterTop;
  32735. serializationObject.diameterBottom = this.diameterBottom;
  32736. serializationObject.tessellation = this.tessellation;
  32737. return serializationObject;
  32738. };
  32739. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  32740. if (scene.getGeometryByID(parsedCylinder.id)) {
  32741. return null; // null since geometry could be something else than a cylinder...
  32742. }
  32743. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32744. if (BABYLON.Tags) {
  32745. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32746. }
  32747. scene.pushGeometry(cylinder, true);
  32748. return cylinder;
  32749. };
  32750. return CylinderGeometry;
  32751. }(_PrimitiveGeometry));
  32752. BABYLON.CylinderGeometry = CylinderGeometry;
  32753. var TorusGeometry = /** @class */ (function (_super) {
  32754. __extends(TorusGeometry, _super);
  32755. function TorusGeometry(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32756. if (mesh === void 0) { mesh = null; }
  32757. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32758. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32759. _this.diameter = diameter;
  32760. _this.thickness = thickness;
  32761. _this.tessellation = tessellation;
  32762. _this.side = side;
  32763. return _this;
  32764. }
  32765. TorusGeometry.prototype._regenerateVertexData = function () {
  32766. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32767. };
  32768. TorusGeometry.prototype.copy = function (id) {
  32769. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32770. };
  32771. TorusGeometry.prototype.serialize = function () {
  32772. var serializationObject = _super.prototype.serialize.call(this);
  32773. serializationObject.diameter = this.diameter;
  32774. serializationObject.thickness = this.thickness;
  32775. serializationObject.tessellation = this.tessellation;
  32776. return serializationObject;
  32777. };
  32778. TorusGeometry.Parse = function (parsedTorus, scene) {
  32779. if (scene.getGeometryByID(parsedTorus.id)) {
  32780. return null; // null since geometry could be something else than a torus...
  32781. }
  32782. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32783. if (BABYLON.Tags) {
  32784. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32785. }
  32786. scene.pushGeometry(torus, true);
  32787. return torus;
  32788. };
  32789. return TorusGeometry;
  32790. }(_PrimitiveGeometry));
  32791. BABYLON.TorusGeometry = TorusGeometry;
  32792. var GroundGeometry = /** @class */ (function (_super) {
  32793. __extends(GroundGeometry, _super);
  32794. function GroundGeometry(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32795. if (mesh === void 0) { mesh = null; }
  32796. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32797. _this.width = width;
  32798. _this.height = height;
  32799. _this.subdivisions = subdivisions;
  32800. return _this;
  32801. }
  32802. GroundGeometry.prototype._regenerateVertexData = function () {
  32803. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32804. };
  32805. GroundGeometry.prototype.copy = function (id) {
  32806. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32807. };
  32808. GroundGeometry.prototype.serialize = function () {
  32809. var serializationObject = _super.prototype.serialize.call(this);
  32810. serializationObject.width = this.width;
  32811. serializationObject.height = this.height;
  32812. serializationObject.subdivisions = this.subdivisions;
  32813. return serializationObject;
  32814. };
  32815. GroundGeometry.Parse = function (parsedGround, scene) {
  32816. if (scene.getGeometryByID(parsedGround.id)) {
  32817. return null; // null since geometry could be something else than a ground...
  32818. }
  32819. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32820. if (BABYLON.Tags) {
  32821. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32822. }
  32823. scene.pushGeometry(ground, true);
  32824. return ground;
  32825. };
  32826. return GroundGeometry;
  32827. }(_PrimitiveGeometry));
  32828. BABYLON.GroundGeometry = GroundGeometry;
  32829. var TiledGroundGeometry = /** @class */ (function (_super) {
  32830. __extends(TiledGroundGeometry, _super);
  32831. function TiledGroundGeometry(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32832. if (mesh === void 0) { mesh = null; }
  32833. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32834. _this.xmin = xmin;
  32835. _this.zmin = zmin;
  32836. _this.xmax = xmax;
  32837. _this.zmax = zmax;
  32838. _this.subdivisions = subdivisions;
  32839. _this.precision = precision;
  32840. return _this;
  32841. }
  32842. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  32843. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32844. };
  32845. TiledGroundGeometry.prototype.copy = function (id) {
  32846. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32847. };
  32848. return TiledGroundGeometry;
  32849. }(_PrimitiveGeometry));
  32850. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  32851. var PlaneGeometry = /** @class */ (function (_super) {
  32852. __extends(PlaneGeometry, _super);
  32853. function PlaneGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32854. if (mesh === void 0) { mesh = null; }
  32855. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32856. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32857. _this.size = size;
  32858. _this.side = side;
  32859. return _this;
  32860. }
  32861. PlaneGeometry.prototype._regenerateVertexData = function () {
  32862. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32863. };
  32864. PlaneGeometry.prototype.copy = function (id) {
  32865. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32866. };
  32867. PlaneGeometry.prototype.serialize = function () {
  32868. var serializationObject = _super.prototype.serialize.call(this);
  32869. serializationObject.size = this.size;
  32870. return serializationObject;
  32871. };
  32872. PlaneGeometry.Parse = function (parsedPlane, scene) {
  32873. if (scene.getGeometryByID(parsedPlane.id)) {
  32874. return null; // null since geometry could be something else than a ground...
  32875. }
  32876. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32877. if (BABYLON.Tags) {
  32878. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32879. }
  32880. scene.pushGeometry(plane, true);
  32881. return plane;
  32882. };
  32883. return PlaneGeometry;
  32884. }(_PrimitiveGeometry));
  32885. BABYLON.PlaneGeometry = PlaneGeometry;
  32886. var TorusKnotGeometry = /** @class */ (function (_super) {
  32887. __extends(TorusKnotGeometry, _super);
  32888. function TorusKnotGeometry(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32889. if (mesh === void 0) { mesh = null; }
  32890. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32891. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32892. _this.radius = radius;
  32893. _this.tube = tube;
  32894. _this.radialSegments = radialSegments;
  32895. _this.tubularSegments = tubularSegments;
  32896. _this.p = p;
  32897. _this.q = q;
  32898. _this.side = side;
  32899. return _this;
  32900. }
  32901. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  32902. 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 });
  32903. };
  32904. TorusKnotGeometry.prototype.copy = function (id) {
  32905. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32906. };
  32907. TorusKnotGeometry.prototype.serialize = function () {
  32908. var serializationObject = _super.prototype.serialize.call(this);
  32909. serializationObject.radius = this.radius;
  32910. serializationObject.tube = this.tube;
  32911. serializationObject.radialSegments = this.radialSegments;
  32912. serializationObject.tubularSegments = this.tubularSegments;
  32913. serializationObject.p = this.p;
  32914. serializationObject.q = this.q;
  32915. return serializationObject;
  32916. };
  32917. ;
  32918. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  32919. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32920. return null; // null since geometry could be something else than a ground...
  32921. }
  32922. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32923. if (BABYLON.Tags) {
  32924. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32925. }
  32926. scene.pushGeometry(torusKnot, true);
  32927. return torusKnot;
  32928. };
  32929. return TorusKnotGeometry;
  32930. }(_PrimitiveGeometry));
  32931. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  32932. //}
  32933. })(BABYLON || (BABYLON = {}));
  32934. //# sourceMappingURL=babylon.geometry.js.map
  32935. var BABYLON;
  32936. (function (BABYLON) {
  32937. var PostProcessManager = /** @class */ (function () {
  32938. function PostProcessManager(scene) {
  32939. this._vertexBuffers = {};
  32940. this._scene = scene;
  32941. }
  32942. PostProcessManager.prototype._prepareBuffers = function () {
  32943. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32944. return;
  32945. }
  32946. // VBO
  32947. var vertices = [];
  32948. vertices.push(1, 1);
  32949. vertices.push(-1, 1);
  32950. vertices.push(-1, -1);
  32951. vertices.push(1, -1);
  32952. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32953. this._buildIndexBuffer();
  32954. };
  32955. PostProcessManager.prototype._buildIndexBuffer = function () {
  32956. // Indices
  32957. var indices = [];
  32958. indices.push(0);
  32959. indices.push(1);
  32960. indices.push(2);
  32961. indices.push(0);
  32962. indices.push(2);
  32963. indices.push(3);
  32964. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32965. };
  32966. PostProcessManager.prototype._rebuild = function () {
  32967. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32968. if (!vb) {
  32969. return;
  32970. }
  32971. vb._rebuild();
  32972. this._buildIndexBuffer();
  32973. };
  32974. // Methods
  32975. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32976. if (sourceTexture === void 0) { sourceTexture = null; }
  32977. if (postProcesses === void 0) { postProcesses = null; }
  32978. var camera = this._scene.activeCamera;
  32979. if (!camera) {
  32980. return false;
  32981. }
  32982. var postProcesses = postProcesses || camera._postProcesses;
  32983. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32984. return false;
  32985. }
  32986. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32987. return true;
  32988. };
  32989. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32990. if (targetTexture === void 0) { targetTexture = null; }
  32991. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32992. var engine = this._scene.getEngine();
  32993. for (var index = 0; index < postProcesses.length; index++) {
  32994. if (index < postProcesses.length - 1) {
  32995. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32996. }
  32997. else {
  32998. if (targetTexture) {
  32999. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  33000. }
  33001. else {
  33002. engine.restoreDefaultFramebuffer();
  33003. }
  33004. }
  33005. var pp = postProcesses[index];
  33006. var effect = pp.apply();
  33007. if (effect) {
  33008. pp.onBeforeRenderObservable.notifyObservers(effect);
  33009. // VBOs
  33010. this._prepareBuffers();
  33011. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33012. // Draw order
  33013. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  33014. pp.onAfterRenderObservable.notifyObservers(effect);
  33015. }
  33016. }
  33017. // Restore depth buffer
  33018. engine.setDepthBuffer(true);
  33019. engine.setDepthWrite(true);
  33020. };
  33021. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  33022. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  33023. var camera = this._scene.activeCamera;
  33024. if (!camera) {
  33025. return;
  33026. }
  33027. postProcesses = postProcesses || camera._postProcesses;
  33028. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  33029. return;
  33030. }
  33031. var engine = this._scene.getEngine();
  33032. for (var index = 0, len = postProcesses.length; index < len; index++) {
  33033. if (index < len - 1) {
  33034. postProcesses[index + 1].activate(camera, targetTexture);
  33035. }
  33036. else {
  33037. if (targetTexture) {
  33038. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  33039. }
  33040. else {
  33041. engine.restoreDefaultFramebuffer();
  33042. }
  33043. }
  33044. if (doNotPresent) {
  33045. break;
  33046. }
  33047. var pp = postProcesses[index];
  33048. var effect = pp.apply();
  33049. if (effect) {
  33050. pp.onBeforeRenderObservable.notifyObservers(effect);
  33051. // VBOs
  33052. this._prepareBuffers();
  33053. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33054. // Draw order
  33055. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  33056. pp.onAfterRenderObservable.notifyObservers(effect);
  33057. }
  33058. }
  33059. // Restore states
  33060. engine.setDepthBuffer(true);
  33061. engine.setDepthWrite(true);
  33062. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33063. };
  33064. PostProcessManager.prototype.dispose = function () {
  33065. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33066. if (buffer) {
  33067. buffer.dispose();
  33068. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  33069. }
  33070. if (this._indexBuffer) {
  33071. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33072. this._indexBuffer = null;
  33073. }
  33074. };
  33075. return PostProcessManager;
  33076. }());
  33077. BABYLON.PostProcessManager = PostProcessManager;
  33078. })(BABYLON || (BABYLON = {}));
  33079. //# sourceMappingURL=babylon.postProcessManager.js.map
  33080. var BABYLON;
  33081. (function (BABYLON) {
  33082. /**
  33083. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  33084. */
  33085. var PerformanceMonitor = /** @class */ (function () {
  33086. /**
  33087. * constructor
  33088. * @param frameSampleSize The number of samples required to saturate the sliding window
  33089. */
  33090. function PerformanceMonitor(frameSampleSize) {
  33091. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  33092. this._enabled = true;
  33093. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  33094. }
  33095. /**
  33096. * Samples current frame
  33097. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  33098. */
  33099. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  33100. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  33101. if (!this._enabled)
  33102. return;
  33103. if (this._lastFrameTimeMs != null) {
  33104. var dt = timeMs - this._lastFrameTimeMs;
  33105. this._rollingFrameTime.add(dt);
  33106. }
  33107. this._lastFrameTimeMs = timeMs;
  33108. };
  33109. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  33110. /**
  33111. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  33112. * @return Average frame time in milliseconds
  33113. */
  33114. get: function () {
  33115. return this._rollingFrameTime.average;
  33116. },
  33117. enumerable: true,
  33118. configurable: true
  33119. });
  33120. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  33121. /**
  33122. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  33123. * @return Frame time variance in milliseconds squared
  33124. */
  33125. get: function () {
  33126. return this._rollingFrameTime.variance;
  33127. },
  33128. enumerable: true,
  33129. configurable: true
  33130. });
  33131. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  33132. /**
  33133. * Returns the frame time of the most recent frame
  33134. * @return Frame time in milliseconds
  33135. */
  33136. get: function () {
  33137. return this._rollingFrameTime.history(0);
  33138. },
  33139. enumerable: true,
  33140. configurable: true
  33141. });
  33142. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  33143. /**
  33144. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  33145. * @return Framerate in frames per second
  33146. */
  33147. get: function () {
  33148. return 1000.0 / this._rollingFrameTime.average;
  33149. },
  33150. enumerable: true,
  33151. configurable: true
  33152. });
  33153. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  33154. /**
  33155. * Returns the average framerate in frames per second using the most recent frame time
  33156. * @return Framerate in frames per second
  33157. */
  33158. get: function () {
  33159. var history = this._rollingFrameTime.history(0);
  33160. if (history === 0) {
  33161. return 0;
  33162. }
  33163. return 1000.0 / history;
  33164. },
  33165. enumerable: true,
  33166. configurable: true
  33167. });
  33168. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  33169. /**
  33170. * Returns true if enough samples have been taken to completely fill the sliding window
  33171. * @return true if saturated
  33172. */
  33173. get: function () {
  33174. return this._rollingFrameTime.isSaturated();
  33175. },
  33176. enumerable: true,
  33177. configurable: true
  33178. });
  33179. /**
  33180. * Enables contributions to the sliding window sample set
  33181. */
  33182. PerformanceMonitor.prototype.enable = function () {
  33183. this._enabled = true;
  33184. };
  33185. /**
  33186. * Disables contributions to the sliding window sample set
  33187. * Samples will not be interpolated over the disabled period
  33188. */
  33189. PerformanceMonitor.prototype.disable = function () {
  33190. this._enabled = false;
  33191. //clear last sample to avoid interpolating over the disabled period when next enabled
  33192. this._lastFrameTimeMs = null;
  33193. };
  33194. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  33195. /**
  33196. * Returns true if sampling is enabled
  33197. * @return true if enabled
  33198. */
  33199. get: function () {
  33200. return this._enabled;
  33201. },
  33202. enumerable: true,
  33203. configurable: true
  33204. });
  33205. /**
  33206. * Resets performance monitor
  33207. */
  33208. PerformanceMonitor.prototype.reset = function () {
  33209. //clear last sample to avoid interpolating over the disabled period when next enabled
  33210. this._lastFrameTimeMs = null;
  33211. //wipe record
  33212. this._rollingFrameTime.reset();
  33213. };
  33214. return PerformanceMonitor;
  33215. }());
  33216. BABYLON.PerformanceMonitor = PerformanceMonitor;
  33217. /**
  33218. * RollingAverage
  33219. *
  33220. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  33221. */
  33222. var RollingAverage = /** @class */ (function () {
  33223. /**
  33224. * constructor
  33225. * @param length The number of samples required to saturate the sliding window
  33226. */
  33227. function RollingAverage(length) {
  33228. this._samples = new Array(length);
  33229. this.reset();
  33230. }
  33231. /**
  33232. * Adds a sample to the sample set
  33233. * @param v The sample value
  33234. */
  33235. RollingAverage.prototype.add = function (v) {
  33236. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  33237. var delta;
  33238. //we need to check if we've already wrapped round
  33239. if (this.isSaturated()) {
  33240. //remove bottom of stack from mean
  33241. var bottomValue = this._samples[this._pos];
  33242. delta = bottomValue - this.average;
  33243. this.average -= delta / (this._sampleCount - 1);
  33244. this._m2 -= delta * (bottomValue - this.average);
  33245. }
  33246. else {
  33247. this._sampleCount++;
  33248. }
  33249. //add new value to mean
  33250. delta = v - this.average;
  33251. this.average += delta / (this._sampleCount);
  33252. this._m2 += delta * (v - this.average);
  33253. //set the new variance
  33254. this.variance = this._m2 / (this._sampleCount - 1);
  33255. this._samples[this._pos] = v;
  33256. this._pos++;
  33257. this._pos %= this._samples.length; //positive wrap around
  33258. };
  33259. /**
  33260. * Returns previously added values or null if outside of history or outside the sliding window domain
  33261. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  33262. * @return Value previously recorded with add() or null if outside of range
  33263. */
  33264. RollingAverage.prototype.history = function (i) {
  33265. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  33266. return 0;
  33267. }
  33268. var i0 = this._wrapPosition(this._pos - 1.0);
  33269. return this._samples[this._wrapPosition(i0 - i)];
  33270. };
  33271. /**
  33272. * Returns true if enough samples have been taken to completely fill the sliding window
  33273. * @return true if sample-set saturated
  33274. */
  33275. RollingAverage.prototype.isSaturated = function () {
  33276. return this._sampleCount >= this._samples.length;
  33277. };
  33278. /**
  33279. * Resets the rolling average (equivalent to 0 samples taken so far)
  33280. */
  33281. RollingAverage.prototype.reset = function () {
  33282. this.average = 0;
  33283. this.variance = 0;
  33284. this._sampleCount = 0;
  33285. this._pos = 0;
  33286. this._m2 = 0;
  33287. };
  33288. /**
  33289. * Wraps a value around the sample range boundaries
  33290. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  33291. * @return Wrapped position in sample range
  33292. */
  33293. RollingAverage.prototype._wrapPosition = function (i) {
  33294. var max = this._samples.length;
  33295. return ((i % max) + max) % max;
  33296. };
  33297. return RollingAverage;
  33298. }());
  33299. BABYLON.RollingAverage = RollingAverage;
  33300. })(BABYLON || (BABYLON = {}));
  33301. //# sourceMappingURL=babylon.performanceMonitor.js.map
  33302. var BABYLON;
  33303. (function (BABYLON) {
  33304. /**
  33305. * This groups together the common properties used for image processing either in direct forward pass
  33306. * or through post processing effect depending on the use of the image processing pipeline in your scene
  33307. * or not.
  33308. */
  33309. var ImageProcessingConfiguration = /** @class */ (function () {
  33310. function ImageProcessingConfiguration() {
  33311. /**
  33312. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  33313. */
  33314. this.colorCurves = new BABYLON.ColorCurves();
  33315. this._colorCurvesEnabled = false;
  33316. this._colorGradingEnabled = false;
  33317. this._colorGradingWithGreenDepth = true;
  33318. this._colorGradingBGR = true;
  33319. this._exposure = 1.0;
  33320. this._toneMappingEnabled = false;
  33321. this._contrast = 1.0;
  33322. /**
  33323. * Vignette stretch size.
  33324. */
  33325. this.vignetteStretch = 0;
  33326. /**
  33327. * Vignette centre X Offset.
  33328. */
  33329. this.vignetteCentreX = 0;
  33330. /**
  33331. * Vignette centre Y Offset.
  33332. */
  33333. this.vignetteCentreY = 0;
  33334. /**
  33335. * Vignette weight or intensity of the vignette effect.
  33336. */
  33337. this.vignetteWeight = 1.5;
  33338. /**
  33339. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  33340. * if vignetteEnabled is set to true.
  33341. */
  33342. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  33343. /**
  33344. * Camera field of view used by the Vignette effect.
  33345. */
  33346. this.vignetteCameraFov = 0.5;
  33347. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  33348. this._vignetteEnabled = false;
  33349. this._applyByPostProcess = false;
  33350. this._isEnabled = true;
  33351. /**
  33352. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  33353. * @type {BABYLON.Observable}
  33354. */
  33355. this.onUpdateParameters = new BABYLON.Observable();
  33356. }
  33357. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  33358. /**
  33359. * Gets wether the color curves effect is enabled.
  33360. */
  33361. get: function () {
  33362. return this._colorCurvesEnabled;
  33363. },
  33364. /**
  33365. * Sets wether the color curves effect is enabled.
  33366. */
  33367. set: function (value) {
  33368. if (this._colorCurvesEnabled === value) {
  33369. return;
  33370. }
  33371. this._colorCurvesEnabled = value;
  33372. this._updateParameters();
  33373. },
  33374. enumerable: true,
  33375. configurable: true
  33376. });
  33377. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  33378. /**
  33379. * Gets wether the color grading effect is enabled.
  33380. */
  33381. get: function () {
  33382. return this._colorGradingEnabled;
  33383. },
  33384. /**
  33385. * Sets wether the color grading effect is enabled.
  33386. */
  33387. set: function (value) {
  33388. if (this._colorGradingEnabled === value) {
  33389. return;
  33390. }
  33391. this._colorGradingEnabled = value;
  33392. this._updateParameters();
  33393. },
  33394. enumerable: true,
  33395. configurable: true
  33396. });
  33397. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  33398. /**
  33399. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  33400. */
  33401. get: function () {
  33402. return this._colorGradingWithGreenDepth;
  33403. },
  33404. /**
  33405. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  33406. */
  33407. set: function (value) {
  33408. if (this._colorGradingWithGreenDepth === value) {
  33409. return;
  33410. }
  33411. this._colorGradingWithGreenDepth = value;
  33412. this._updateParameters();
  33413. },
  33414. enumerable: true,
  33415. configurable: true
  33416. });
  33417. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  33418. /**
  33419. * Gets wether the color grading texture contains BGR values.
  33420. */
  33421. get: function () {
  33422. return this._colorGradingBGR;
  33423. },
  33424. /**
  33425. * Sets wether the color grading texture contains BGR values.
  33426. */
  33427. set: function (value) {
  33428. if (this._colorGradingBGR === value) {
  33429. return;
  33430. }
  33431. this._colorGradingBGR = value;
  33432. this._updateParameters();
  33433. },
  33434. enumerable: true,
  33435. configurable: true
  33436. });
  33437. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  33438. /**
  33439. * Gets the Exposure used in the effect.
  33440. */
  33441. get: function () {
  33442. return this._exposure;
  33443. },
  33444. /**
  33445. * Sets the Exposure used in the effect.
  33446. */
  33447. set: function (value) {
  33448. if (this._exposure === value) {
  33449. return;
  33450. }
  33451. this._exposure = value;
  33452. this._updateParameters();
  33453. },
  33454. enumerable: true,
  33455. configurable: true
  33456. });
  33457. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  33458. /**
  33459. * Gets wether the tone mapping effect is enabled.
  33460. */
  33461. get: function () {
  33462. return this._toneMappingEnabled;
  33463. },
  33464. /**
  33465. * Sets wether the tone mapping effect is enabled.
  33466. */
  33467. set: function (value) {
  33468. if (this._toneMappingEnabled === value) {
  33469. return;
  33470. }
  33471. this._toneMappingEnabled = value;
  33472. this._updateParameters();
  33473. },
  33474. enumerable: true,
  33475. configurable: true
  33476. });
  33477. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  33478. /**
  33479. * Gets the contrast used in the effect.
  33480. */
  33481. get: function () {
  33482. return this._contrast;
  33483. },
  33484. /**
  33485. * Sets the contrast used in the effect.
  33486. */
  33487. set: function (value) {
  33488. if (this._contrast === value) {
  33489. return;
  33490. }
  33491. this._contrast = value;
  33492. this._updateParameters();
  33493. },
  33494. enumerable: true,
  33495. configurable: true
  33496. });
  33497. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  33498. /**
  33499. * Gets the vignette blend mode allowing different kind of effect.
  33500. */
  33501. get: function () {
  33502. return this._vignetteBlendMode;
  33503. },
  33504. /**
  33505. * Sets the vignette blend mode allowing different kind of effect.
  33506. */
  33507. set: function (value) {
  33508. if (this._vignetteBlendMode === value) {
  33509. return;
  33510. }
  33511. this._vignetteBlendMode = value;
  33512. this._updateParameters();
  33513. },
  33514. enumerable: true,
  33515. configurable: true
  33516. });
  33517. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  33518. /**
  33519. * Gets wether the vignette effect is enabled.
  33520. */
  33521. get: function () {
  33522. return this._vignetteEnabled;
  33523. },
  33524. /**
  33525. * Sets wether the vignette effect is enabled.
  33526. */
  33527. set: function (value) {
  33528. if (this._vignetteEnabled === value) {
  33529. return;
  33530. }
  33531. this._vignetteEnabled = value;
  33532. this._updateParameters();
  33533. },
  33534. enumerable: true,
  33535. configurable: true
  33536. });
  33537. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  33538. /**
  33539. * Gets wether the image processing is applied through a post process or not.
  33540. */
  33541. get: function () {
  33542. return this._applyByPostProcess;
  33543. },
  33544. /**
  33545. * Sets wether the image processing is applied through a post process or not.
  33546. */
  33547. set: function (value) {
  33548. if (this._applyByPostProcess === value) {
  33549. return;
  33550. }
  33551. this._applyByPostProcess = value;
  33552. this._updateParameters();
  33553. },
  33554. enumerable: true,
  33555. configurable: true
  33556. });
  33557. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  33558. /**
  33559. * Gets wether the image processing is enabled or not.
  33560. */
  33561. get: function () {
  33562. return this._isEnabled;
  33563. },
  33564. /**
  33565. * Sets wether the image processing is enabled or not.
  33566. */
  33567. set: function (value) {
  33568. if (this._isEnabled === value) {
  33569. return;
  33570. }
  33571. this._isEnabled = value;
  33572. this._updateParameters();
  33573. },
  33574. enumerable: true,
  33575. configurable: true
  33576. });
  33577. /**
  33578. * Method called each time the image processing information changes requires to recompile the effect.
  33579. */
  33580. ImageProcessingConfiguration.prototype._updateParameters = function () {
  33581. this.onUpdateParameters.notifyObservers(this);
  33582. };
  33583. ImageProcessingConfiguration.prototype.getClassName = function () {
  33584. return "ImageProcessingConfiguration";
  33585. };
  33586. /**
  33587. * Prepare the list of uniforms associated with the Image Processing effects.
  33588. * @param uniformsList The list of uniforms used in the effect
  33589. * @param defines the list of defines currently in use
  33590. */
  33591. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  33592. if (defines.EXPOSURE) {
  33593. uniforms.push("exposureLinear");
  33594. }
  33595. if (defines.CONTRAST) {
  33596. uniforms.push("contrast");
  33597. }
  33598. if (defines.COLORGRADING) {
  33599. uniforms.push("colorTransformSettings");
  33600. }
  33601. if (defines.VIGNETTE) {
  33602. uniforms.push("vInverseScreenSize");
  33603. uniforms.push("vignetteSettings1");
  33604. uniforms.push("vignetteSettings2");
  33605. }
  33606. if (defines.COLORCURVES) {
  33607. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  33608. }
  33609. };
  33610. /**
  33611. * Prepare the list of samplers associated with the Image Processing effects.
  33612. * @param uniformsList The list of uniforms used in the effect
  33613. * @param defines the list of defines currently in use
  33614. */
  33615. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  33616. if (defines.COLORGRADING) {
  33617. samplersList.push("txColorTransform");
  33618. }
  33619. };
  33620. /**
  33621. * Prepare the list of defines associated to the shader.
  33622. * @param defines the list of defines to complete
  33623. */
  33624. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  33625. if (forPostProcess === void 0) { forPostProcess = false; }
  33626. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  33627. defines.VIGNETTE = false;
  33628. defines.TONEMAPPING = false;
  33629. defines.CONTRAST = false;
  33630. defines.EXPOSURE = false;
  33631. defines.COLORCURVES = false;
  33632. defines.COLORGRADING = false;
  33633. defines.COLORGRADING3D = false;
  33634. defines.IMAGEPROCESSING = false;
  33635. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  33636. return;
  33637. }
  33638. defines.VIGNETTE = this.vignetteEnabled;
  33639. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  33640. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  33641. defines.TONEMAPPING = this.toneMappingEnabled;
  33642. defines.CONTRAST = (this.contrast !== 1.0);
  33643. defines.EXPOSURE = (this.exposure !== 1.0);
  33644. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  33645. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  33646. if (defines.COLORGRADING) {
  33647. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  33648. }
  33649. else {
  33650. defines.COLORGRADING3D = false;
  33651. }
  33652. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  33653. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  33654. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  33655. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  33656. };
  33657. /**
  33658. * Returns true if all the image processing information are ready.
  33659. */
  33660. ImageProcessingConfiguration.prototype.isReady = function () {
  33661. // Color Grading texure can not be none blocking.
  33662. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  33663. };
  33664. /**
  33665. * Binds the image processing to the shader.
  33666. * @param effect The effect to bind to
  33667. */
  33668. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  33669. if (aspectRatio === void 0) { aspectRatio = 1; }
  33670. // Color Curves
  33671. if (this._colorCurvesEnabled && this.colorCurves) {
  33672. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33673. }
  33674. // Vignette
  33675. if (this._vignetteEnabled) {
  33676. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33677. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33678. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33679. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33680. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33681. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33682. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33683. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33684. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33685. var vignettePower = -2.0 * this.vignetteWeight;
  33686. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33687. }
  33688. // Exposure
  33689. effect.setFloat("exposureLinear", this.exposure);
  33690. // Contrast
  33691. effect.setFloat("contrast", this.contrast);
  33692. // Color transform settings
  33693. if (this.colorGradingTexture) {
  33694. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33695. var textureSize = this.colorGradingTexture.getSize().height;
  33696. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33697. 0.5 / textureSize, // textureOffset
  33698. textureSize, // textureSize
  33699. this.colorGradingTexture.level // weight
  33700. );
  33701. }
  33702. };
  33703. /**
  33704. * Clones the current image processing instance.
  33705. * @return The cloned image processing
  33706. */
  33707. ImageProcessingConfiguration.prototype.clone = function () {
  33708. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33709. };
  33710. /**
  33711. * Serializes the current image processing instance to a json representation.
  33712. * @return a JSON representation
  33713. */
  33714. ImageProcessingConfiguration.prototype.serialize = function () {
  33715. return BABYLON.SerializationHelper.Serialize(this);
  33716. };
  33717. /**
  33718. * Parses the image processing from a json representation.
  33719. * @param source the JSON source to parse
  33720. * @return The parsed image processing
  33721. */
  33722. ImageProcessingConfiguration.Parse = function (source) {
  33723. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33724. };
  33725. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33726. /**
  33727. * Used to apply the vignette as a mix with the pixel color.
  33728. */
  33729. get: function () {
  33730. return this._VIGNETTEMODE_MULTIPLY;
  33731. },
  33732. enumerable: true,
  33733. configurable: true
  33734. });
  33735. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33736. /**
  33737. * Used to apply the vignette as a replacement of the pixel color.
  33738. */
  33739. get: function () {
  33740. return this._VIGNETTEMODE_OPAQUE;
  33741. },
  33742. enumerable: true,
  33743. configurable: true
  33744. });
  33745. // Static constants associated to the image processing.
  33746. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33747. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33748. __decorate([
  33749. BABYLON.serializeAsColorCurves()
  33750. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33751. __decorate([
  33752. BABYLON.serialize()
  33753. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33754. __decorate([
  33755. BABYLON.serializeAsTexture()
  33756. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33757. __decorate([
  33758. BABYLON.serialize()
  33759. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33760. __decorate([
  33761. BABYLON.serialize()
  33762. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33763. __decorate([
  33764. BABYLON.serialize()
  33765. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33766. __decorate([
  33767. BABYLON.serialize()
  33768. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33769. __decorate([
  33770. BABYLON.serialize()
  33771. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33772. __decorate([
  33773. BABYLON.serialize()
  33774. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33775. __decorate([
  33776. BABYLON.serialize()
  33777. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33778. __decorate([
  33779. BABYLON.serialize()
  33780. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33781. __decorate([
  33782. BABYLON.serialize()
  33783. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33784. __decorate([
  33785. BABYLON.serialize()
  33786. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33787. __decorate([
  33788. BABYLON.serializeAsColor4()
  33789. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33790. __decorate([
  33791. BABYLON.serialize()
  33792. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33793. __decorate([
  33794. BABYLON.serialize()
  33795. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33796. __decorate([
  33797. BABYLON.serialize()
  33798. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33799. __decorate([
  33800. BABYLON.serialize()
  33801. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33802. __decorate([
  33803. BABYLON.serialize()
  33804. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33805. return ImageProcessingConfiguration;
  33806. }());
  33807. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33808. })(BABYLON || (BABYLON = {}));
  33809. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33810. var BABYLON;
  33811. (function (BABYLON) {
  33812. /**
  33813. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33814. * It can help converting any input color in a desired output one. This can then be used to create effects
  33815. * from sepia, black and white to sixties or futuristic rendering...
  33816. *
  33817. * The only supported format is currently 3dl.
  33818. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33819. */
  33820. var ColorGradingTexture = /** @class */ (function (_super) {
  33821. __extends(ColorGradingTexture, _super);
  33822. /**
  33823. * Instantiates a ColorGradingTexture from the following parameters.
  33824. *
  33825. * @param url The location of the color gradind data (currently only supporting 3dl)
  33826. * @param scene The scene the texture will be used in
  33827. */
  33828. function ColorGradingTexture(url, scene) {
  33829. var _this = _super.call(this, scene) || this;
  33830. if (!url) {
  33831. return _this;
  33832. }
  33833. _this._engine = scene.getEngine();
  33834. _this._textureMatrix = BABYLON.Matrix.Identity();
  33835. _this.name = url;
  33836. _this.url = url;
  33837. _this.hasAlpha = false;
  33838. _this.isCube = false;
  33839. _this.is3D = _this._engine.webGLVersion > 1;
  33840. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33841. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33842. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33843. _this.anisotropicFilteringLevel = 1;
  33844. _this._texture = _this._getFromCache(url, true);
  33845. if (!_this._texture) {
  33846. if (!scene.useDelayedTextureLoading) {
  33847. _this.loadTexture();
  33848. }
  33849. else {
  33850. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33851. }
  33852. }
  33853. return _this;
  33854. }
  33855. /**
  33856. * Returns the texture matrix used in most of the material.
  33857. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33858. */
  33859. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33860. return this._textureMatrix;
  33861. };
  33862. /**
  33863. * Occurs when the file being loaded is a .3dl LUT file.
  33864. */
  33865. ColorGradingTexture.prototype.load3dlTexture = function () {
  33866. var engine = this._engine;
  33867. var texture;
  33868. if (engine.webGLVersion === 1) {
  33869. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33870. }
  33871. else {
  33872. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33873. }
  33874. this._texture = texture;
  33875. var callback = function (text) {
  33876. if (typeof text !== "string") {
  33877. return;
  33878. }
  33879. var data = null;
  33880. var tempData = null;
  33881. var line;
  33882. var lines = text.split('\n');
  33883. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33884. var maxColor = 0;
  33885. for (var i = 0; i < lines.length; i++) {
  33886. line = lines[i];
  33887. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33888. continue;
  33889. if (line.indexOf('#') === 0)
  33890. continue;
  33891. var words = line.split(" ");
  33892. if (size === 0) {
  33893. // Number of space + one
  33894. size = words.length;
  33895. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33896. tempData = new Float32Array(size * size * size * 4);
  33897. continue;
  33898. }
  33899. if (size != 0) {
  33900. var r = Math.max(parseInt(words[0]), 0);
  33901. var g = Math.max(parseInt(words[1]), 0);
  33902. var b = Math.max(parseInt(words[2]), 0);
  33903. maxColor = Math.max(r, maxColor);
  33904. maxColor = Math.max(g, maxColor);
  33905. maxColor = Math.max(b, maxColor);
  33906. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33907. if (tempData) {
  33908. tempData[pixelStorageIndex + 0] = r;
  33909. tempData[pixelStorageIndex + 1] = g;
  33910. tempData[pixelStorageIndex + 2] = b;
  33911. }
  33912. pixelIndexSlice++;
  33913. if (pixelIndexSlice % size == 0) {
  33914. pixelIndexH++;
  33915. pixelIndexSlice = 0;
  33916. if (pixelIndexH % size == 0) {
  33917. pixelIndexW++;
  33918. pixelIndexH = 0;
  33919. }
  33920. }
  33921. }
  33922. }
  33923. if (tempData && data) {
  33924. for (var i = 0; i < tempData.length; i++) {
  33925. if (i > 0 && (i + 1) % 4 === 0) {
  33926. data[i] = 255;
  33927. }
  33928. else {
  33929. var value = tempData[i];
  33930. data[i] = (value / maxColor * 255);
  33931. }
  33932. }
  33933. }
  33934. if (texture.is3D) {
  33935. texture.updateSize(size, size, size);
  33936. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33937. }
  33938. else {
  33939. texture.updateSize(size * size, size);
  33940. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33941. }
  33942. };
  33943. var scene = this.getScene();
  33944. if (scene) {
  33945. scene._loadFile(this.url, callback);
  33946. }
  33947. else {
  33948. this._engine._loadFile(this.url, callback);
  33949. }
  33950. return this._texture;
  33951. };
  33952. /**
  33953. * Starts the loading process of the texture.
  33954. */
  33955. ColorGradingTexture.prototype.loadTexture = function () {
  33956. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33957. this.load3dlTexture();
  33958. }
  33959. };
  33960. /**
  33961. * Clones the color gradind texture.
  33962. */
  33963. ColorGradingTexture.prototype.clone = function () {
  33964. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33965. // Base texture
  33966. newTexture.level = this.level;
  33967. return newTexture;
  33968. };
  33969. /**
  33970. * Called during delayed load for textures.
  33971. */
  33972. ColorGradingTexture.prototype.delayLoad = function () {
  33973. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33974. return;
  33975. }
  33976. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33977. this._texture = this._getFromCache(this.url, true);
  33978. if (!this._texture) {
  33979. this.loadTexture();
  33980. }
  33981. };
  33982. /**
  33983. * Parses a color grading texture serialized by Babylon.
  33984. * @param parsedTexture The texture information being parsedTexture
  33985. * @param scene The scene to load the texture in
  33986. * @param rootUrl The root url of the data assets to load
  33987. * @return A color gradind texture
  33988. */
  33989. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33990. var texture = null;
  33991. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33992. texture = new ColorGradingTexture(parsedTexture.name, scene);
  33993. texture.name = parsedTexture.name;
  33994. texture.level = parsedTexture.level;
  33995. }
  33996. return texture;
  33997. };
  33998. /**
  33999. * Serializes the LUT texture to json format.
  34000. */
  34001. ColorGradingTexture.prototype.serialize = function () {
  34002. if (!this.name) {
  34003. return null;
  34004. }
  34005. var serializationObject = {};
  34006. serializationObject.name = this.name;
  34007. serializationObject.level = this.level;
  34008. serializationObject.customType = "BABYLON.ColorGradingTexture";
  34009. return serializationObject;
  34010. };
  34011. /**
  34012. * Empty line regex stored for GC.
  34013. */
  34014. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  34015. return ColorGradingTexture;
  34016. }(BABYLON.BaseTexture));
  34017. BABYLON.ColorGradingTexture = ColorGradingTexture;
  34018. })(BABYLON || (BABYLON = {}));
  34019. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  34020. var BABYLON;
  34021. (function (BABYLON) {
  34022. /**
  34023. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34024. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34025. * 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;
  34026. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34027. */
  34028. var ColorCurves = /** @class */ (function () {
  34029. function ColorCurves() {
  34030. this._dirty = true;
  34031. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  34032. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  34033. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  34034. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  34035. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  34036. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  34037. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  34038. this._globalHue = 30;
  34039. this._globalDensity = 0;
  34040. this._globalSaturation = 0;
  34041. this._globalExposure = 0;
  34042. this._highlightsHue = 30;
  34043. this._highlightsDensity = 0;
  34044. this._highlightsSaturation = 0;
  34045. this._highlightsExposure = 0;
  34046. this._midtonesHue = 30;
  34047. this._midtonesDensity = 0;
  34048. this._midtonesSaturation = 0;
  34049. this._midtonesExposure = 0;
  34050. this._shadowsHue = 30;
  34051. this._shadowsDensity = 0;
  34052. this._shadowsSaturation = 0;
  34053. this._shadowsExposure = 0;
  34054. }
  34055. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  34056. /**
  34057. * Gets the global Hue value.
  34058. * 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).
  34059. */
  34060. get: function () {
  34061. return this._globalHue;
  34062. },
  34063. /**
  34064. * Sets the global Hue value.
  34065. * 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).
  34066. */
  34067. set: function (value) {
  34068. this._globalHue = value;
  34069. this._dirty = true;
  34070. },
  34071. enumerable: true,
  34072. configurable: true
  34073. });
  34074. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  34075. /**
  34076. * Gets the global Density value.
  34077. * 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.
  34078. * Values less than zero provide a filter of opposite hue.
  34079. */
  34080. get: function () {
  34081. return this._globalDensity;
  34082. },
  34083. /**
  34084. * Sets the global Density value.
  34085. * 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.
  34086. * Values less than zero provide a filter of opposite hue.
  34087. */
  34088. set: function (value) {
  34089. this._globalDensity = value;
  34090. this._dirty = true;
  34091. },
  34092. enumerable: true,
  34093. configurable: true
  34094. });
  34095. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  34096. /**
  34097. * Gets the global Saturation value.
  34098. * 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.
  34099. */
  34100. get: function () {
  34101. return this._globalSaturation;
  34102. },
  34103. /**
  34104. * Sets the global Saturation value.
  34105. * 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.
  34106. */
  34107. set: function (value) {
  34108. this._globalSaturation = value;
  34109. this._dirty = true;
  34110. },
  34111. enumerable: true,
  34112. configurable: true
  34113. });
  34114. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  34115. /**
  34116. * Gets the highlights Hue value.
  34117. * 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).
  34118. */
  34119. get: function () {
  34120. return this._highlightsHue;
  34121. },
  34122. /**
  34123. * Sets the highlights Hue value.
  34124. * 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).
  34125. */
  34126. set: function (value) {
  34127. this._highlightsHue = value;
  34128. this._dirty = true;
  34129. },
  34130. enumerable: true,
  34131. configurable: true
  34132. });
  34133. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  34134. /**
  34135. * Gets the highlights Density value.
  34136. * 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.
  34137. * Values less than zero provide a filter of opposite hue.
  34138. */
  34139. get: function () {
  34140. return this._highlightsDensity;
  34141. },
  34142. /**
  34143. * Sets the highlights Density value.
  34144. * 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.
  34145. * Values less than zero provide a filter of opposite hue.
  34146. */
  34147. set: function (value) {
  34148. this._highlightsDensity = value;
  34149. this._dirty = true;
  34150. },
  34151. enumerable: true,
  34152. configurable: true
  34153. });
  34154. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  34155. /**
  34156. * Gets the highlights Saturation value.
  34157. * 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.
  34158. */
  34159. get: function () {
  34160. return this._highlightsSaturation;
  34161. },
  34162. /**
  34163. * Sets the highlights Saturation value.
  34164. * 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.
  34165. */
  34166. set: function (value) {
  34167. this._highlightsSaturation = value;
  34168. this._dirty = true;
  34169. },
  34170. enumerable: true,
  34171. configurable: true
  34172. });
  34173. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  34174. /**
  34175. * Gets the highlights Exposure value.
  34176. * 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.
  34177. */
  34178. get: function () {
  34179. return this._highlightsExposure;
  34180. },
  34181. /**
  34182. * Sets the highlights Exposure value.
  34183. * 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.
  34184. */
  34185. set: function (value) {
  34186. this._highlightsExposure = value;
  34187. this._dirty = true;
  34188. },
  34189. enumerable: true,
  34190. configurable: true
  34191. });
  34192. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  34193. /**
  34194. * Gets the midtones Hue value.
  34195. * 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).
  34196. */
  34197. get: function () {
  34198. return this._midtonesHue;
  34199. },
  34200. /**
  34201. * Sets the midtones Hue value.
  34202. * 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).
  34203. */
  34204. set: function (value) {
  34205. this._midtonesHue = value;
  34206. this._dirty = true;
  34207. },
  34208. enumerable: true,
  34209. configurable: true
  34210. });
  34211. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  34212. /**
  34213. * Gets the midtones Density value.
  34214. * 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.
  34215. * Values less than zero provide a filter of opposite hue.
  34216. */
  34217. get: function () {
  34218. return this._midtonesDensity;
  34219. },
  34220. /**
  34221. * Sets the midtones Density value.
  34222. * 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.
  34223. * Values less than zero provide a filter of opposite hue.
  34224. */
  34225. set: function (value) {
  34226. this._midtonesDensity = value;
  34227. this._dirty = true;
  34228. },
  34229. enumerable: true,
  34230. configurable: true
  34231. });
  34232. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  34233. /**
  34234. * Gets the midtones Saturation value.
  34235. * 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.
  34236. */
  34237. get: function () {
  34238. return this._midtonesSaturation;
  34239. },
  34240. /**
  34241. * Sets the midtones Saturation value.
  34242. * 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.
  34243. */
  34244. set: function (value) {
  34245. this._midtonesSaturation = value;
  34246. this._dirty = true;
  34247. },
  34248. enumerable: true,
  34249. configurable: true
  34250. });
  34251. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  34252. /**
  34253. * Gets the midtones Exposure value.
  34254. * 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.
  34255. */
  34256. get: function () {
  34257. return this._midtonesExposure;
  34258. },
  34259. /**
  34260. * Sets the midtones Exposure value.
  34261. * 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.
  34262. */
  34263. set: function (value) {
  34264. this._midtonesExposure = value;
  34265. this._dirty = true;
  34266. },
  34267. enumerable: true,
  34268. configurable: true
  34269. });
  34270. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  34271. /**
  34272. * Gets the shadows Hue value.
  34273. * 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).
  34274. */
  34275. get: function () {
  34276. return this._shadowsHue;
  34277. },
  34278. /**
  34279. * Sets the shadows Hue value.
  34280. * 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).
  34281. */
  34282. set: function (value) {
  34283. this._shadowsHue = value;
  34284. this._dirty = true;
  34285. },
  34286. enumerable: true,
  34287. configurable: true
  34288. });
  34289. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  34290. /**
  34291. * Gets the shadows Density value.
  34292. * 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.
  34293. * Values less than zero provide a filter of opposite hue.
  34294. */
  34295. get: function () {
  34296. return this._shadowsDensity;
  34297. },
  34298. /**
  34299. * Sets the shadows Density value.
  34300. * 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.
  34301. * Values less than zero provide a filter of opposite hue.
  34302. */
  34303. set: function (value) {
  34304. this._shadowsDensity = value;
  34305. this._dirty = true;
  34306. },
  34307. enumerable: true,
  34308. configurable: true
  34309. });
  34310. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  34311. /**
  34312. * Gets the shadows Saturation value.
  34313. * 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.
  34314. */
  34315. get: function () {
  34316. return this._shadowsSaturation;
  34317. },
  34318. /**
  34319. * Sets the shadows Saturation value.
  34320. * 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.
  34321. */
  34322. set: function (value) {
  34323. this._shadowsSaturation = value;
  34324. this._dirty = true;
  34325. },
  34326. enumerable: true,
  34327. configurable: true
  34328. });
  34329. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  34330. /**
  34331. * Gets the shadows Exposure value.
  34332. * 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.
  34333. */
  34334. get: function () {
  34335. return this._shadowsExposure;
  34336. },
  34337. /**
  34338. * Sets the shadows Exposure value.
  34339. * 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.
  34340. */
  34341. set: function (value) {
  34342. this._shadowsExposure = value;
  34343. this._dirty = true;
  34344. },
  34345. enumerable: true,
  34346. configurable: true
  34347. });
  34348. ColorCurves.prototype.getClassName = function () {
  34349. return "ColorCurves";
  34350. };
  34351. /**
  34352. * Binds the color curves to the shader.
  34353. * @param colorCurves The color curve to bind
  34354. * @param effect The effect to bind to
  34355. */
  34356. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  34357. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  34358. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  34359. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  34360. if (colorCurves._dirty) {
  34361. colorCurves._dirty = false;
  34362. // Fill in global info.
  34363. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  34364. // Compute highlights info.
  34365. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  34366. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  34367. // Compute midtones info.
  34368. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  34369. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  34370. // Compute shadows info.
  34371. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  34372. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  34373. // Compute deltas (neutral is midtones).
  34374. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  34375. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  34376. }
  34377. if (effect) {
  34378. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  34379. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  34380. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  34381. }
  34382. };
  34383. /**
  34384. * Prepare the list of uniforms associated with the ColorCurves effects.
  34385. * @param uniformsList The list of uniforms used in the effect
  34386. */
  34387. ColorCurves.PrepareUniforms = function (uniformsList) {
  34388. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  34389. };
  34390. /**
  34391. * Returns color grading data based on a hue, density, saturation and exposure value.
  34392. * @param filterHue The hue of the color filter.
  34393. * @param filterDensity The density of the color filter.
  34394. * @param saturation The saturation.
  34395. * @param exposure The exposure.
  34396. * @param result The result data container.
  34397. */
  34398. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  34399. if (hue == null) {
  34400. return;
  34401. }
  34402. hue = ColorCurves.clamp(hue, 0, 360);
  34403. density = ColorCurves.clamp(density, -100, 100);
  34404. saturation = ColorCurves.clamp(saturation, -100, 100);
  34405. exposure = ColorCurves.clamp(exposure, -100, 100);
  34406. // Remap the slider/config filter density with non-linear mapping and also scale by half
  34407. // so that the maximum filter density is only 50% control. This provides fine control
  34408. // for small values and reasonable range.
  34409. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  34410. density *= 0.5;
  34411. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  34412. if (density < 0) {
  34413. density *= -1;
  34414. hue = (hue + 180) % 360;
  34415. }
  34416. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  34417. result.scaleToRef(2, result);
  34418. result.a = 1 + 0.01 * saturation;
  34419. };
  34420. /**
  34421. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  34422. * @param value The input slider value in range [-100,100].
  34423. * @returns Adjusted value.
  34424. */
  34425. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  34426. value /= 100;
  34427. var x = Math.abs(value);
  34428. x = Math.pow(x, 2);
  34429. if (value < 0) {
  34430. x *= -1;
  34431. }
  34432. x *= 100;
  34433. return x;
  34434. };
  34435. /**
  34436. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  34437. * @param hue The hue (H) input.
  34438. * @param saturation The saturation (S) input.
  34439. * @param brightness The brightness (B) input.
  34440. * @result An RGBA color represented as Vector4.
  34441. */
  34442. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  34443. var h = ColorCurves.clamp(hue, 0, 360);
  34444. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  34445. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  34446. if (s === 0) {
  34447. result.r = v;
  34448. result.g = v;
  34449. result.b = v;
  34450. }
  34451. else {
  34452. // sector 0 to 5
  34453. h /= 60;
  34454. var i = Math.floor(h);
  34455. // fractional part of h
  34456. var f = h - i;
  34457. var p = v * (1 - s);
  34458. var q = v * (1 - s * f);
  34459. var t = v * (1 - s * (1 - f));
  34460. switch (i) {
  34461. case 0:
  34462. result.r = v;
  34463. result.g = t;
  34464. result.b = p;
  34465. break;
  34466. case 1:
  34467. result.r = q;
  34468. result.g = v;
  34469. result.b = p;
  34470. break;
  34471. case 2:
  34472. result.r = p;
  34473. result.g = v;
  34474. result.b = t;
  34475. break;
  34476. case 3:
  34477. result.r = p;
  34478. result.g = q;
  34479. result.b = v;
  34480. break;
  34481. case 4:
  34482. result.r = t;
  34483. result.g = p;
  34484. result.b = v;
  34485. break;
  34486. default:// case 5:
  34487. result.r = v;
  34488. result.g = p;
  34489. result.b = q;
  34490. break;
  34491. }
  34492. }
  34493. result.a = 1;
  34494. };
  34495. /**
  34496. * Returns a value clamped between min and max
  34497. * @param value The value to clamp
  34498. * @param min The minimum of value
  34499. * @param max The maximum of value
  34500. * @returns The clamped value.
  34501. */
  34502. ColorCurves.clamp = function (value, min, max) {
  34503. return Math.min(Math.max(value, min), max);
  34504. };
  34505. /**
  34506. * Clones the current color curve instance.
  34507. * @return The cloned curves
  34508. */
  34509. ColorCurves.prototype.clone = function () {
  34510. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  34511. };
  34512. /**
  34513. * Serializes the current color curve instance to a json representation.
  34514. * @return a JSON representation
  34515. */
  34516. ColorCurves.prototype.serialize = function () {
  34517. return BABYLON.SerializationHelper.Serialize(this);
  34518. };
  34519. /**
  34520. * Parses the color curve from a json representation.
  34521. * @param source the JSON source to parse
  34522. * @return The parsed curves
  34523. */
  34524. ColorCurves.Parse = function (source) {
  34525. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  34526. };
  34527. __decorate([
  34528. BABYLON.serialize()
  34529. ], ColorCurves.prototype, "_globalHue", void 0);
  34530. __decorate([
  34531. BABYLON.serialize()
  34532. ], ColorCurves.prototype, "_globalDensity", void 0);
  34533. __decorate([
  34534. BABYLON.serialize()
  34535. ], ColorCurves.prototype, "_globalSaturation", void 0);
  34536. __decorate([
  34537. BABYLON.serialize()
  34538. ], ColorCurves.prototype, "_globalExposure", void 0);
  34539. __decorate([
  34540. BABYLON.serialize()
  34541. ], ColorCurves.prototype, "_highlightsHue", void 0);
  34542. __decorate([
  34543. BABYLON.serialize()
  34544. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  34545. __decorate([
  34546. BABYLON.serialize()
  34547. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  34548. __decorate([
  34549. BABYLON.serialize()
  34550. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  34551. __decorate([
  34552. BABYLON.serialize()
  34553. ], ColorCurves.prototype, "_midtonesHue", void 0);
  34554. __decorate([
  34555. BABYLON.serialize()
  34556. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  34557. __decorate([
  34558. BABYLON.serialize()
  34559. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  34560. __decorate([
  34561. BABYLON.serialize()
  34562. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  34563. return ColorCurves;
  34564. }());
  34565. BABYLON.ColorCurves = ColorCurves;
  34566. })(BABYLON || (BABYLON = {}));
  34567. //# sourceMappingURL=babylon.colorCurves.js.map
  34568. //# sourceMappingURL=babylon.behavior.js.map
  34569. var BABYLON;
  34570. (function (BABYLON) {
  34571. var MaterialHelper = /** @class */ (function () {
  34572. function MaterialHelper() {
  34573. }
  34574. MaterialHelper.BindEyePosition = function (effect, scene) {
  34575. if (scene._forcedViewPosition) {
  34576. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  34577. return;
  34578. }
  34579. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  34580. };
  34581. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  34582. defines._needUVs = true;
  34583. defines[key] = true;
  34584. if (texture.getTextureMatrix().isIdentity(true)) {
  34585. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  34586. if (texture.coordinatesIndex === 0) {
  34587. defines["MAINUV1"] = true;
  34588. }
  34589. else {
  34590. defines["MAINUV2"] = true;
  34591. }
  34592. }
  34593. else {
  34594. defines[key + "DIRECTUV"] = 0;
  34595. }
  34596. };
  34597. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  34598. var matrix = texture.getTextureMatrix();
  34599. if (!matrix.isIdentity(true)) {
  34600. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  34601. }
  34602. };
  34603. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  34604. if (defines._areMiscDirty) {
  34605. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  34606. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  34607. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  34608. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  34609. }
  34610. };
  34611. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  34612. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  34613. var changed = false;
  34614. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  34615. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  34616. changed = true;
  34617. }
  34618. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  34619. defines["ALPHATEST"] = !defines["ALPHATEST"];
  34620. changed = true;
  34621. }
  34622. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  34623. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  34624. changed = true;
  34625. }
  34626. if (defines["INSTANCES"] !== useInstances) {
  34627. defines["INSTANCES"] = useInstances;
  34628. changed = true;
  34629. }
  34630. if (changed) {
  34631. defines.markAsUnprocessed();
  34632. }
  34633. };
  34634. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  34635. if (useMorphTargets === void 0) { useMorphTargets = false; }
  34636. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  34637. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  34638. return false;
  34639. }
  34640. defines._normals = defines._needNormals;
  34641. defines._uvs = defines._needUVs;
  34642. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  34643. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34644. defines["TANGENT"] = true;
  34645. }
  34646. if (defines._needUVs) {
  34647. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  34648. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  34649. }
  34650. else {
  34651. defines["UV1"] = false;
  34652. defines["UV2"] = false;
  34653. }
  34654. if (useVertexColor) {
  34655. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  34656. defines["VERTEXCOLOR"] = hasVertexColors;
  34657. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  34658. }
  34659. if (useBones) {
  34660. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34661. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  34662. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  34663. }
  34664. else {
  34665. defines["NUM_BONE_INFLUENCERS"] = 0;
  34666. defines["BonesPerMesh"] = 0;
  34667. }
  34668. }
  34669. if (useMorphTargets) {
  34670. var manager = mesh.morphTargetManager;
  34671. if (manager) {
  34672. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  34673. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  34674. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  34675. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  34676. }
  34677. else {
  34678. defines["MORPHTARGETS_TANGENT"] = false;
  34679. defines["MORPHTARGETS_NORMAL"] = false;
  34680. defines["MORPHTARGETS"] = false;
  34681. defines["NUM_MORPH_INFLUENCERS"] = 0;
  34682. }
  34683. }
  34684. return true;
  34685. };
  34686. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  34687. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34688. if (disableLighting === void 0) { disableLighting = false; }
  34689. if (!defines._areLightsDirty) {
  34690. return defines._needNormals;
  34691. }
  34692. var lightIndex = 0;
  34693. var needNormals = false;
  34694. var needRebuild = false;
  34695. var lightmapMode = false;
  34696. var shadowEnabled = false;
  34697. var specularEnabled = false;
  34698. if (scene.lightsEnabled && !disableLighting) {
  34699. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34700. var light = _a[_i];
  34701. needNormals = true;
  34702. if (defines["LIGHT" + lightIndex] === undefined) {
  34703. needRebuild = true;
  34704. }
  34705. defines["LIGHT" + lightIndex] = true;
  34706. defines["SPOTLIGHT" + lightIndex] = false;
  34707. defines["HEMILIGHT" + lightIndex] = false;
  34708. defines["POINTLIGHT" + lightIndex] = false;
  34709. defines["DIRLIGHT" + lightIndex] = false;
  34710. var type;
  34711. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  34712. type = "SPOTLIGHT" + lightIndex;
  34713. }
  34714. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  34715. type = "HEMILIGHT" + lightIndex;
  34716. }
  34717. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  34718. type = "POINTLIGHT" + lightIndex;
  34719. }
  34720. else {
  34721. type = "DIRLIGHT" + lightIndex;
  34722. }
  34723. defines[type] = true;
  34724. // Specular
  34725. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  34726. specularEnabled = true;
  34727. }
  34728. // Shadows
  34729. defines["SHADOW" + lightIndex] = false;
  34730. defines["SHADOWPCF" + lightIndex] = false;
  34731. defines["SHADOWESM" + lightIndex] = false;
  34732. defines["SHADOWCUBE" + lightIndex] = false;
  34733. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  34734. var shadowGenerator = light.getShadowGenerator();
  34735. if (shadowGenerator) {
  34736. shadowEnabled = true;
  34737. shadowGenerator.prepareDefines(defines, lightIndex);
  34738. }
  34739. }
  34740. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  34741. lightmapMode = true;
  34742. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  34743. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  34744. }
  34745. else {
  34746. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  34747. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  34748. }
  34749. lightIndex++;
  34750. if (lightIndex === maxSimultaneousLights)
  34751. break;
  34752. }
  34753. }
  34754. defines["SPECULARTERM"] = specularEnabled;
  34755. defines["SHADOWS"] = shadowEnabled;
  34756. // Resetting all other lights if any
  34757. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  34758. if (defines["LIGHT" + index] !== undefined) {
  34759. defines["LIGHT" + index] = false;
  34760. defines["HEMILIGHT" + lightIndex] = false;
  34761. defines["POINTLIGHT" + lightIndex] = false;
  34762. defines["DIRLIGHT" + lightIndex] = false;
  34763. defines["SPOTLIGHT" + lightIndex] = false;
  34764. defines["SHADOW" + lightIndex] = false;
  34765. }
  34766. }
  34767. var caps = scene.getEngine().getCaps();
  34768. if (defines["SHADOWFLOAT"] === undefined) {
  34769. needRebuild = true;
  34770. }
  34771. defines["SHADOWFLOAT"] = shadowEnabled &&
  34772. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  34773. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  34774. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  34775. if (needRebuild) {
  34776. defines.rebuild();
  34777. }
  34778. return needNormals;
  34779. };
  34780. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  34781. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34782. var uniformsList;
  34783. var uniformBuffersList = null;
  34784. if (uniformsListOrOptions.uniformsNames) {
  34785. var options = uniformsListOrOptions;
  34786. uniformsList = options.uniformsNames;
  34787. uniformBuffersList = options.uniformBuffersNames;
  34788. samplersList = options.samplers;
  34789. defines = options.defines;
  34790. maxSimultaneousLights = options.maxSimultaneousLights;
  34791. }
  34792. else {
  34793. uniformsList = uniformsListOrOptions;
  34794. if (!samplersList) {
  34795. samplersList = [];
  34796. }
  34797. }
  34798. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34799. if (!defines["LIGHT" + lightIndex]) {
  34800. break;
  34801. }
  34802. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  34803. if (uniformBuffersList) {
  34804. uniformBuffersList.push("Light" + lightIndex);
  34805. }
  34806. samplersList.push("shadowSampler" + lightIndex);
  34807. }
  34808. if (defines["NUM_MORPH_INFLUENCERS"]) {
  34809. uniformsList.push("morphTargetInfluences");
  34810. }
  34811. };
  34812. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  34813. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34814. if (rank === void 0) { rank = 0; }
  34815. var lightFallbackRank = 0;
  34816. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34817. if (!defines["LIGHT" + lightIndex]) {
  34818. break;
  34819. }
  34820. if (lightIndex > 0) {
  34821. lightFallbackRank = rank + lightIndex;
  34822. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  34823. }
  34824. if (!defines["SHADOWS"]) {
  34825. if (defines["SHADOW" + lightIndex]) {
  34826. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  34827. }
  34828. if (defines["SHADOWPCF" + lightIndex]) {
  34829. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  34830. }
  34831. if (defines["SHADOWESM" + lightIndex]) {
  34832. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  34833. }
  34834. }
  34835. }
  34836. return lightFallbackRank++;
  34837. };
  34838. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  34839. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  34840. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  34841. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  34842. var manager = mesh.morphTargetManager;
  34843. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  34844. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  34845. for (var index = 0; index < influencers; index++) {
  34846. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  34847. if (normal) {
  34848. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  34849. }
  34850. if (tangent) {
  34851. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  34852. }
  34853. if (attribs.length > maxAttributesCount) {
  34854. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  34855. }
  34856. }
  34857. }
  34858. };
  34859. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  34860. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  34861. fallbacks.addCPUSkinningFallback(0, mesh);
  34862. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34863. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34864. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  34865. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34866. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34867. }
  34868. }
  34869. };
  34870. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  34871. if (defines["INSTANCES"]) {
  34872. attribs.push("world0");
  34873. attribs.push("world1");
  34874. attribs.push("world2");
  34875. attribs.push("world3");
  34876. }
  34877. };
  34878. // Bindings
  34879. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  34880. if (light.shadowEnabled && mesh.receiveShadows) {
  34881. var shadowGenerator = light.getShadowGenerator();
  34882. if (shadowGenerator) {
  34883. shadowGenerator.bindShadowLight(lightIndex, effect);
  34884. }
  34885. }
  34886. };
  34887. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  34888. light.transferToEffect(effect, lightIndex + "");
  34889. };
  34890. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  34891. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34892. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  34893. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  34894. for (var i = 0; i < len; i++) {
  34895. var light = mesh._lightSources[i];
  34896. var iAsString = i.toString();
  34897. var scaledIntensity = light.getScaledIntensity();
  34898. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  34899. MaterialHelper.BindLightProperties(light, effect, i);
  34900. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  34901. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  34902. if (defines["SPECULARTERM"]) {
  34903. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  34904. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  34905. }
  34906. // Shadows
  34907. if (scene.shadowsEnabled) {
  34908. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  34909. }
  34910. light._uniformBuffer.update();
  34911. }
  34912. };
  34913. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  34914. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34915. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34916. effect.setColor3("vFogColor", scene.fogColor);
  34917. }
  34918. };
  34919. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  34920. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34921. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  34922. if (matrices && effect) {
  34923. effect.setMatrices("mBones", matrices);
  34924. }
  34925. }
  34926. };
  34927. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  34928. var manager = abstractMesh.morphTargetManager;
  34929. if (!abstractMesh || !manager) {
  34930. return;
  34931. }
  34932. effect.setFloatArray("morphTargetInfluences", manager.influences);
  34933. };
  34934. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  34935. if (defines["LOGARITHMICDEPTH"]) {
  34936. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  34937. }
  34938. };
  34939. MaterialHelper.BindClipPlane = function (effect, scene) {
  34940. if (scene.clipPlane) {
  34941. var clipPlane = scene.clipPlane;
  34942. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34943. }
  34944. };
  34945. return MaterialHelper;
  34946. }());
  34947. BABYLON.MaterialHelper = MaterialHelper;
  34948. })(BABYLON || (BABYLON = {}));
  34949. //# sourceMappingURL=babylon.materialHelper.js.map
  34950. var BABYLON;
  34951. (function (BABYLON) {
  34952. var PushMaterial = /** @class */ (function (_super) {
  34953. __extends(PushMaterial, _super);
  34954. function PushMaterial(name, scene) {
  34955. var _this = _super.call(this, name, scene) || this;
  34956. _this.storeEffectOnSubMeshes = true;
  34957. return _this;
  34958. }
  34959. PushMaterial.prototype.getEffect = function () {
  34960. return this._activeEffect;
  34961. };
  34962. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  34963. if (!mesh) {
  34964. return false;
  34965. }
  34966. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  34967. return true;
  34968. }
  34969. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  34970. };
  34971. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34972. this._activeEffect.setMatrix("world", world);
  34973. };
  34974. PushMaterial.prototype.bind = function (world, mesh) {
  34975. if (!mesh) {
  34976. return;
  34977. }
  34978. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  34979. };
  34980. PushMaterial.prototype._afterBind = function (mesh, effect) {
  34981. if (effect === void 0) { effect = null; }
  34982. _super.prototype._afterBind.call(this, mesh);
  34983. this.getScene()._cachedEffect = effect;
  34984. };
  34985. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  34986. if (visibility === void 0) { visibility = 1; }
  34987. return scene.isCachedMaterialInvalid(this, effect, visibility);
  34988. };
  34989. return PushMaterial;
  34990. }(BABYLON.Material));
  34991. BABYLON.PushMaterial = PushMaterial;
  34992. })(BABYLON || (BABYLON = {}));
  34993. //# sourceMappingURL=babylon.pushMaterial.js.map
  34994. var BABYLON;
  34995. (function (BABYLON) {
  34996. var StandardMaterialDefines = /** @class */ (function (_super) {
  34997. __extends(StandardMaterialDefines, _super);
  34998. function StandardMaterialDefines() {
  34999. var _this = _super.call(this) || this;
  35000. _this.MAINUV1 = false;
  35001. _this.MAINUV2 = false;
  35002. _this.DIFFUSE = false;
  35003. _this.DIFFUSEDIRECTUV = 0;
  35004. _this.AMBIENT = false;
  35005. _this.AMBIENTDIRECTUV = 0;
  35006. _this.OPACITY = false;
  35007. _this.OPACITYDIRECTUV = 0;
  35008. _this.OPACITYRGB = false;
  35009. _this.REFLECTION = false;
  35010. _this.EMISSIVE = false;
  35011. _this.EMISSIVEDIRECTUV = 0;
  35012. _this.SPECULAR = false;
  35013. _this.SPECULARDIRECTUV = 0;
  35014. _this.BUMP = false;
  35015. _this.BUMPDIRECTUV = 0;
  35016. _this.PARALLAX = false;
  35017. _this.PARALLAXOCCLUSION = false;
  35018. _this.SPECULAROVERALPHA = false;
  35019. _this.CLIPPLANE = false;
  35020. _this.ALPHATEST = false;
  35021. _this.DEPTHPREPASS = false;
  35022. _this.ALPHAFROMDIFFUSE = false;
  35023. _this.POINTSIZE = false;
  35024. _this.FOG = false;
  35025. _this.SPECULARTERM = false;
  35026. _this.DIFFUSEFRESNEL = false;
  35027. _this.OPACITYFRESNEL = false;
  35028. _this.REFLECTIONFRESNEL = false;
  35029. _this.REFRACTIONFRESNEL = false;
  35030. _this.EMISSIVEFRESNEL = false;
  35031. _this.FRESNEL = false;
  35032. _this.NORMAL = false;
  35033. _this.UV1 = false;
  35034. _this.UV2 = false;
  35035. _this.VERTEXCOLOR = false;
  35036. _this.VERTEXALPHA = false;
  35037. _this.NUM_BONE_INFLUENCERS = 0;
  35038. _this.BonesPerMesh = 0;
  35039. _this.INSTANCES = false;
  35040. _this.GLOSSINESS = false;
  35041. _this.ROUGHNESS = false;
  35042. _this.EMISSIVEASILLUMINATION = false;
  35043. _this.LINKEMISSIVEWITHDIFFUSE = false;
  35044. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  35045. _this.LIGHTMAP = false;
  35046. _this.LIGHTMAPDIRECTUV = 0;
  35047. _this.USELIGHTMAPASSHADOWMAP = false;
  35048. _this.REFLECTIONMAP_3D = false;
  35049. _this.REFLECTIONMAP_SPHERICAL = false;
  35050. _this.REFLECTIONMAP_PLANAR = false;
  35051. _this.REFLECTIONMAP_CUBIC = false;
  35052. _this.REFLECTIONMAP_PROJECTION = false;
  35053. _this.REFLECTIONMAP_SKYBOX = false;
  35054. _this.REFLECTIONMAP_EXPLICIT = false;
  35055. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35056. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35057. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35058. _this.INVERTCUBICMAP = false;
  35059. _this.LOGARITHMICDEPTH = false;
  35060. _this.REFRACTION = false;
  35061. _this.REFRACTIONMAP_3D = false;
  35062. _this.REFLECTIONOVERALPHA = false;
  35063. _this.TWOSIDEDLIGHTING = false;
  35064. _this.SHADOWFLOAT = false;
  35065. _this.MORPHTARGETS = false;
  35066. _this.MORPHTARGETS_NORMAL = false;
  35067. _this.MORPHTARGETS_TANGENT = false;
  35068. _this.NUM_MORPH_INFLUENCERS = 0;
  35069. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  35070. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  35071. _this.IMAGEPROCESSING = false;
  35072. _this.VIGNETTE = false;
  35073. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35074. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35075. _this.TONEMAPPING = false;
  35076. _this.CONTRAST = false;
  35077. _this.COLORCURVES = false;
  35078. _this.COLORGRADING = false;
  35079. _this.COLORGRADING3D = false;
  35080. _this.SAMPLER3DGREENDEPTH = false;
  35081. _this.SAMPLER3DBGRMAP = false;
  35082. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35083. _this.EXPOSURE = false;
  35084. _this.rebuild();
  35085. return _this;
  35086. }
  35087. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  35088. var modes = [
  35089. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  35090. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  35091. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  35092. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  35093. ];
  35094. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  35095. var mode = modes_1[_i];
  35096. this[mode] = (mode === modeToEnable);
  35097. }
  35098. };
  35099. return StandardMaterialDefines;
  35100. }(BABYLON.MaterialDefines));
  35101. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  35102. var StandardMaterial = /** @class */ (function (_super) {
  35103. __extends(StandardMaterial, _super);
  35104. function StandardMaterial(name, scene) {
  35105. var _this = _super.call(this, name, scene) || this;
  35106. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  35107. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  35108. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  35109. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35110. _this.specularPower = 64;
  35111. _this._useAlphaFromDiffuseTexture = false;
  35112. _this._useEmissiveAsIllumination = false;
  35113. _this._linkEmissiveWithDiffuse = false;
  35114. _this._useSpecularOverAlpha = false;
  35115. _this._useReflectionOverAlpha = false;
  35116. _this._disableLighting = false;
  35117. _this._useParallax = false;
  35118. _this._useParallaxOcclusion = false;
  35119. _this.parallaxScaleBias = 0.05;
  35120. _this._roughness = 0;
  35121. _this.indexOfRefraction = 0.98;
  35122. _this.invertRefractionY = true;
  35123. _this._useLightmapAsShadowmap = false;
  35124. _this._useReflectionFresnelFromSpecular = false;
  35125. _this._useGlossinessFromSpecularMapAlpha = false;
  35126. _this._maxSimultaneousLights = 4;
  35127. /**
  35128. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35129. */
  35130. _this._invertNormalMapX = false;
  35131. /**
  35132. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35133. */
  35134. _this._invertNormalMapY = false;
  35135. /**
  35136. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35137. */
  35138. _this._twoSidedLighting = false;
  35139. _this._renderTargets = new BABYLON.SmartArray(16);
  35140. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  35141. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35142. // Setup the default processing configuration to the scene.
  35143. _this._attachImageProcessingConfiguration(null);
  35144. _this.getRenderTargetTextures = function () {
  35145. _this._renderTargets.reset();
  35146. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35147. _this._renderTargets.push(_this._reflectionTexture);
  35148. }
  35149. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35150. _this._renderTargets.push(_this._refractionTexture);
  35151. }
  35152. return _this._renderTargets;
  35153. };
  35154. return _this;
  35155. }
  35156. ;
  35157. ;
  35158. ;
  35159. ;
  35160. ;
  35161. ;
  35162. ;
  35163. ;
  35164. ;
  35165. ;
  35166. ;
  35167. ;
  35168. ;
  35169. ;
  35170. ;
  35171. ;
  35172. ;
  35173. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  35174. /**
  35175. * Gets the image processing configuration used either in this material.
  35176. */
  35177. get: function () {
  35178. return this._imageProcessingConfiguration;
  35179. },
  35180. /**
  35181. * Sets the Default image processing configuration used either in the this material.
  35182. *
  35183. * If sets to null, the scene one is in use.
  35184. */
  35185. set: function (value) {
  35186. this._attachImageProcessingConfiguration(value);
  35187. // Ensure the effect will be rebuilt.
  35188. this._markAllSubMeshesAsTexturesDirty();
  35189. },
  35190. enumerable: true,
  35191. configurable: true
  35192. });
  35193. /**
  35194. * Attaches a new image processing configuration to the Standard Material.
  35195. * @param configuration
  35196. */
  35197. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35198. var _this = this;
  35199. if (configuration === this._imageProcessingConfiguration) {
  35200. return;
  35201. }
  35202. // Detaches observer.
  35203. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35204. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35205. }
  35206. // Pick the scene configuration if needed.
  35207. if (!configuration) {
  35208. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35209. }
  35210. else {
  35211. this._imageProcessingConfiguration = configuration;
  35212. }
  35213. // Attaches observer.
  35214. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35215. _this._markAllSubMeshesAsImageProcessingDirty();
  35216. });
  35217. };
  35218. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  35219. /**
  35220. * Gets wether the color curves effect is enabled.
  35221. */
  35222. get: function () {
  35223. return this.imageProcessingConfiguration.colorCurvesEnabled;
  35224. },
  35225. /**
  35226. * Sets wether the color curves effect is enabled.
  35227. */
  35228. set: function (value) {
  35229. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  35230. },
  35231. enumerable: true,
  35232. configurable: true
  35233. });
  35234. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  35235. /**
  35236. * Gets wether the color grading effect is enabled.
  35237. */
  35238. get: function () {
  35239. return this.imageProcessingConfiguration.colorGradingEnabled;
  35240. },
  35241. /**
  35242. * Gets wether the color grading effect is enabled.
  35243. */
  35244. set: function (value) {
  35245. this.imageProcessingConfiguration.colorGradingEnabled = value;
  35246. },
  35247. enumerable: true,
  35248. configurable: true
  35249. });
  35250. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  35251. /**
  35252. * Gets wether tonemapping is enabled or not.
  35253. */
  35254. get: function () {
  35255. return this._imageProcessingConfiguration.toneMappingEnabled;
  35256. },
  35257. /**
  35258. * Sets wether tonemapping is enabled or not
  35259. */
  35260. set: function (value) {
  35261. this._imageProcessingConfiguration.toneMappingEnabled = value;
  35262. },
  35263. enumerable: true,
  35264. configurable: true
  35265. });
  35266. ;
  35267. ;
  35268. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  35269. /**
  35270. * The camera exposure used on this material.
  35271. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35272. * This corresponds to a photographic exposure.
  35273. */
  35274. get: function () {
  35275. return this._imageProcessingConfiguration.exposure;
  35276. },
  35277. /**
  35278. * The camera exposure used on this material.
  35279. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35280. * This corresponds to a photographic exposure.
  35281. */
  35282. set: function (value) {
  35283. this._imageProcessingConfiguration.exposure = value;
  35284. },
  35285. enumerable: true,
  35286. configurable: true
  35287. });
  35288. ;
  35289. ;
  35290. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  35291. /**
  35292. * Gets The camera contrast used on this material.
  35293. */
  35294. get: function () {
  35295. return this._imageProcessingConfiguration.contrast;
  35296. },
  35297. /**
  35298. * Sets The camera contrast used on this material.
  35299. */
  35300. set: function (value) {
  35301. this._imageProcessingConfiguration.contrast = value;
  35302. },
  35303. enumerable: true,
  35304. configurable: true
  35305. });
  35306. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  35307. /**
  35308. * Gets the Color Grading 2D Lookup Texture.
  35309. */
  35310. get: function () {
  35311. return this._imageProcessingConfiguration.colorGradingTexture;
  35312. },
  35313. /**
  35314. * Sets the Color Grading 2D Lookup Texture.
  35315. */
  35316. set: function (value) {
  35317. this._imageProcessingConfiguration.colorGradingTexture = value;
  35318. },
  35319. enumerable: true,
  35320. configurable: true
  35321. });
  35322. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  35323. /**
  35324. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35325. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35326. * 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;
  35327. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35328. */
  35329. get: function () {
  35330. return this._imageProcessingConfiguration.colorCurves;
  35331. },
  35332. /**
  35333. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35334. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35335. * 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;
  35336. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35337. */
  35338. set: function (value) {
  35339. this._imageProcessingConfiguration.colorCurves = value;
  35340. },
  35341. enumerable: true,
  35342. configurable: true
  35343. });
  35344. StandardMaterial.prototype.getClassName = function () {
  35345. return "StandardMaterial";
  35346. };
  35347. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  35348. get: function () {
  35349. return this._useLogarithmicDepth;
  35350. },
  35351. set: function (value) {
  35352. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35353. this._markAllSubMeshesAsMiscDirty();
  35354. },
  35355. enumerable: true,
  35356. configurable: true
  35357. });
  35358. StandardMaterial.prototype.needAlphaBlending = function () {
  35359. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  35360. };
  35361. StandardMaterial.prototype.needAlphaTesting = function () {
  35362. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  35363. };
  35364. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  35365. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  35366. };
  35367. StandardMaterial.prototype.getAlphaTestTexture = function () {
  35368. return this._diffuseTexture;
  35369. };
  35370. /**
  35371. * Child classes can use it to update shaders
  35372. */
  35373. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35374. if (useInstances === void 0) { useInstances = false; }
  35375. if (subMesh.effect && this.isFrozen) {
  35376. if (this._wasPreviouslyReady && subMesh.effect) {
  35377. return true;
  35378. }
  35379. }
  35380. if (!subMesh._materialDefines) {
  35381. subMesh._materialDefines = new StandardMaterialDefines();
  35382. }
  35383. var scene = this.getScene();
  35384. var defines = subMesh._materialDefines;
  35385. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35386. if (defines._renderId === scene.getRenderId()) {
  35387. return true;
  35388. }
  35389. }
  35390. var engine = scene.getEngine();
  35391. // Lights
  35392. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35393. // Textures
  35394. if (defines._areTexturesDirty) {
  35395. defines._needUVs = false;
  35396. defines.MAINUV1 = false;
  35397. defines.MAINUV2 = false;
  35398. if (scene.texturesEnabled) {
  35399. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35400. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  35401. return false;
  35402. }
  35403. else {
  35404. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  35405. }
  35406. }
  35407. else {
  35408. defines.DIFFUSE = false;
  35409. }
  35410. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35411. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35412. return false;
  35413. }
  35414. else {
  35415. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35416. }
  35417. }
  35418. else {
  35419. defines.AMBIENT = false;
  35420. }
  35421. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35422. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35423. return false;
  35424. }
  35425. else {
  35426. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35427. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35428. }
  35429. }
  35430. else {
  35431. defines.OPACITY = false;
  35432. }
  35433. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35434. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  35435. return false;
  35436. }
  35437. else {
  35438. defines._needNormals = true;
  35439. defines.REFLECTION = true;
  35440. defines.ROUGHNESS = (this._roughness > 0);
  35441. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  35442. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  35443. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  35444. switch (this._reflectionTexture.coordinatesMode) {
  35445. case BABYLON.Texture.CUBIC_MODE:
  35446. case BABYLON.Texture.INVCUBIC_MODE:
  35447. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  35448. break;
  35449. case BABYLON.Texture.EXPLICIT_MODE:
  35450. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  35451. break;
  35452. case BABYLON.Texture.PLANAR_MODE:
  35453. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  35454. break;
  35455. case BABYLON.Texture.PROJECTION_MODE:
  35456. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  35457. break;
  35458. case BABYLON.Texture.SKYBOX_MODE:
  35459. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  35460. break;
  35461. case BABYLON.Texture.SPHERICAL_MODE:
  35462. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  35463. break;
  35464. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35465. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  35466. break;
  35467. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35468. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  35469. break;
  35470. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35471. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  35472. break;
  35473. }
  35474. }
  35475. }
  35476. else {
  35477. defines.REFLECTION = false;
  35478. }
  35479. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35480. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35481. return false;
  35482. }
  35483. else {
  35484. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35485. }
  35486. }
  35487. else {
  35488. defines.EMISSIVE = false;
  35489. }
  35490. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35491. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35492. return false;
  35493. }
  35494. else {
  35495. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35496. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35497. }
  35498. }
  35499. else {
  35500. defines.LIGHTMAP = false;
  35501. }
  35502. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35503. if (!this._specularTexture.isReadyOrNotBlocking()) {
  35504. return false;
  35505. }
  35506. else {
  35507. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  35508. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  35509. }
  35510. }
  35511. else {
  35512. defines.SPECULAR = false;
  35513. }
  35514. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  35515. // Bump texure can not be not blocking.
  35516. if (!this._bumpTexture.isReady()) {
  35517. return false;
  35518. }
  35519. else {
  35520. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35521. defines.PARALLAX = this._useParallax;
  35522. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  35523. }
  35524. }
  35525. else {
  35526. defines.BUMP = false;
  35527. }
  35528. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35529. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35530. return false;
  35531. }
  35532. else {
  35533. defines._needUVs = true;
  35534. defines.REFRACTION = true;
  35535. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35536. }
  35537. }
  35538. else {
  35539. defines.REFRACTION = false;
  35540. }
  35541. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  35542. }
  35543. else {
  35544. defines.DIFFUSE = false;
  35545. defines.AMBIENT = false;
  35546. defines.OPACITY = false;
  35547. defines.REFLECTION = false;
  35548. defines.EMISSIVE = false;
  35549. defines.LIGHTMAP = false;
  35550. defines.BUMP = false;
  35551. defines.REFRACTION = false;
  35552. }
  35553. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  35554. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  35555. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  35556. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35557. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35558. }
  35559. if (defines._areImageProcessingDirty) {
  35560. if (!this._imageProcessingConfiguration.isReady()) {
  35561. return false;
  35562. }
  35563. this._imageProcessingConfiguration.prepareDefines(defines);
  35564. }
  35565. if (defines._areFresnelDirty) {
  35566. if (StandardMaterial.FresnelEnabled) {
  35567. // Fresnel
  35568. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  35569. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  35570. this._reflectionFresnelParameters) {
  35571. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  35572. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  35573. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  35574. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  35575. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  35576. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  35577. defines._needNormals = true;
  35578. defines.FRESNEL = true;
  35579. }
  35580. }
  35581. else {
  35582. defines.FRESNEL = false;
  35583. }
  35584. }
  35585. // Misc.
  35586. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35587. // Attribs
  35588. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  35589. // Values that need to be evaluated on every frame
  35590. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  35591. // Get correct effect
  35592. if (defines.isDirty) {
  35593. defines.markAsProcessed();
  35594. scene.resetCachedMaterial();
  35595. // Fallbacks
  35596. var fallbacks = new BABYLON.EffectFallbacks();
  35597. if (defines.REFLECTION) {
  35598. fallbacks.addFallback(0, "REFLECTION");
  35599. }
  35600. if (defines.SPECULAR) {
  35601. fallbacks.addFallback(0, "SPECULAR");
  35602. }
  35603. if (defines.BUMP) {
  35604. fallbacks.addFallback(0, "BUMP");
  35605. }
  35606. if (defines.PARALLAX) {
  35607. fallbacks.addFallback(1, "PARALLAX");
  35608. }
  35609. if (defines.PARALLAXOCCLUSION) {
  35610. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35611. }
  35612. if (defines.SPECULAROVERALPHA) {
  35613. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35614. }
  35615. if (defines.FOG) {
  35616. fallbacks.addFallback(1, "FOG");
  35617. }
  35618. if (defines.POINTSIZE) {
  35619. fallbacks.addFallback(0, "POINTSIZE");
  35620. }
  35621. if (defines.LOGARITHMICDEPTH) {
  35622. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35623. }
  35624. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35625. if (defines.SPECULARTERM) {
  35626. fallbacks.addFallback(0, "SPECULARTERM");
  35627. }
  35628. if (defines.DIFFUSEFRESNEL) {
  35629. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  35630. }
  35631. if (defines.OPACITYFRESNEL) {
  35632. fallbacks.addFallback(2, "OPACITYFRESNEL");
  35633. }
  35634. if (defines.REFLECTIONFRESNEL) {
  35635. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  35636. }
  35637. if (defines.EMISSIVEFRESNEL) {
  35638. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  35639. }
  35640. if (defines.FRESNEL) {
  35641. fallbacks.addFallback(4, "FRESNEL");
  35642. }
  35643. //Attributes
  35644. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35645. if (defines.NORMAL) {
  35646. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35647. }
  35648. if (defines.UV1) {
  35649. attribs.push(BABYLON.VertexBuffer.UVKind);
  35650. }
  35651. if (defines.UV2) {
  35652. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35653. }
  35654. if (defines.VERTEXCOLOR) {
  35655. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35656. }
  35657. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35658. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35659. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35660. var shaderName = "default";
  35661. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  35662. "vFogInfos", "vFogColor", "pointSize",
  35663. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35664. "mBones",
  35665. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35666. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  35667. "logarithmicDepthConstant", "vTangentSpaceParams"
  35668. ];
  35669. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35670. var uniformBuffers = ["Material", "Scene"];
  35671. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35672. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35673. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35674. uniformsNames: uniforms,
  35675. uniformBuffersNames: uniformBuffers,
  35676. samplers: samplers,
  35677. defines: defines,
  35678. maxSimultaneousLights: this._maxSimultaneousLights
  35679. });
  35680. if (this.customShaderNameResolve) {
  35681. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35682. }
  35683. var join = defines.toString();
  35684. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35685. attributes: attribs,
  35686. uniformsNames: uniforms,
  35687. uniformBuffersNames: uniformBuffers,
  35688. samplers: samplers,
  35689. defines: join,
  35690. fallbacks: fallbacks,
  35691. onCompiled: this.onCompiled,
  35692. onError: this.onError,
  35693. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35694. }, engine), defines);
  35695. this.buildUniformLayout();
  35696. }
  35697. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35698. return false;
  35699. }
  35700. defines._renderId = scene.getRenderId();
  35701. this._wasPreviouslyReady = true;
  35702. return true;
  35703. };
  35704. StandardMaterial.prototype.buildUniformLayout = function () {
  35705. // Order is important !
  35706. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35707. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35708. this._uniformBuffer.addUniform("opacityParts", 4);
  35709. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35710. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35711. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35712. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35713. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35714. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35715. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35716. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35717. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35718. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35719. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35720. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35721. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35722. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35723. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35724. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35725. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35726. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35727. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35728. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35729. this._uniformBuffer.addUniform("specularMatrix", 16);
  35730. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35731. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35732. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35733. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35734. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35735. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35736. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35737. this._uniformBuffer.addUniform("pointSize", 1);
  35738. this._uniformBuffer.create();
  35739. };
  35740. StandardMaterial.prototype.unbind = function () {
  35741. if (this._activeEffect) {
  35742. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35743. this._activeEffect.setTexture("reflection2DSampler", null);
  35744. }
  35745. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35746. this._activeEffect.setTexture("refraction2DSampler", null);
  35747. }
  35748. }
  35749. _super.prototype.unbind.call(this);
  35750. };
  35751. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35752. var scene = this.getScene();
  35753. var defines = subMesh._materialDefines;
  35754. if (!defines) {
  35755. return;
  35756. }
  35757. var effect = subMesh.effect;
  35758. if (!effect) {
  35759. return;
  35760. }
  35761. this._activeEffect = effect;
  35762. // Matrices
  35763. this.bindOnlyWorldMatrix(world);
  35764. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35765. // Bones
  35766. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35767. if (mustRebind) {
  35768. this._uniformBuffer.bindToEffect(effect, "Material");
  35769. this.bindViewProjection(effect);
  35770. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35771. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35772. // Fresnel
  35773. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35774. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35775. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35776. }
  35777. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35778. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35779. }
  35780. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35781. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35782. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35783. }
  35784. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35785. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35786. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35787. }
  35788. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35789. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35790. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35791. }
  35792. }
  35793. // Textures
  35794. if (scene.texturesEnabled) {
  35795. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35796. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35797. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  35798. }
  35799. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35800. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35801. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35802. }
  35803. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35804. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35805. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35806. }
  35807. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35808. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35809. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35810. }
  35811. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35812. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35813. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35814. }
  35815. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35816. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35817. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35818. }
  35819. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35820. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35821. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  35822. }
  35823. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35824. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35825. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35826. if (scene._mirroredCameraPosition) {
  35827. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35828. }
  35829. else {
  35830. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35831. }
  35832. }
  35833. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35834. var depth = 1.0;
  35835. if (!this._refractionTexture.isCube) {
  35836. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35837. if (this._refractionTexture.depth) {
  35838. depth = this._refractionTexture.depth;
  35839. }
  35840. }
  35841. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35842. }
  35843. }
  35844. // Point size
  35845. if (this.pointsCloud) {
  35846. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35847. }
  35848. if (defines.SPECULARTERM) {
  35849. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35850. }
  35851. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35852. // Diffuse
  35853. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35854. }
  35855. // Textures
  35856. if (scene.texturesEnabled) {
  35857. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35858. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35859. }
  35860. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35861. effect.setTexture("ambientSampler", this._ambientTexture);
  35862. }
  35863. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35864. effect.setTexture("opacitySampler", this._opacityTexture);
  35865. }
  35866. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35867. if (this._reflectionTexture.isCube) {
  35868. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35869. }
  35870. else {
  35871. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35872. }
  35873. }
  35874. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35875. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35876. }
  35877. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35878. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35879. }
  35880. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35881. effect.setTexture("specularSampler", this._specularTexture);
  35882. }
  35883. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35884. effect.setTexture("bumpSampler", this._bumpTexture);
  35885. }
  35886. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35887. var depth = 1.0;
  35888. if (this._refractionTexture.isCube) {
  35889. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35890. }
  35891. else {
  35892. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35893. }
  35894. }
  35895. }
  35896. // Clip plane
  35897. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35898. // Colors
  35899. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35900. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  35901. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35902. }
  35903. if (mustRebind || !this.isFrozen) {
  35904. // Lights
  35905. if (scene.lightsEnabled && !this._disableLighting) {
  35906. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35907. }
  35908. // View
  35909. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35910. this.bindView(effect);
  35911. }
  35912. // Fog
  35913. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35914. // Morph targets
  35915. if (defines.NUM_MORPH_INFLUENCERS) {
  35916. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35917. }
  35918. // Log. depth
  35919. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35920. // image processing
  35921. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  35922. this._imageProcessingConfiguration.bind(this._activeEffect);
  35923. }
  35924. }
  35925. this._uniformBuffer.update();
  35926. this._afterBind(mesh, this._activeEffect);
  35927. };
  35928. StandardMaterial.prototype.getAnimatables = function () {
  35929. var results = [];
  35930. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35931. results.push(this._diffuseTexture);
  35932. }
  35933. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35934. results.push(this._ambientTexture);
  35935. }
  35936. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35937. results.push(this._opacityTexture);
  35938. }
  35939. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35940. results.push(this._reflectionTexture);
  35941. }
  35942. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35943. results.push(this._emissiveTexture);
  35944. }
  35945. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35946. results.push(this._specularTexture);
  35947. }
  35948. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35949. results.push(this._bumpTexture);
  35950. }
  35951. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35952. results.push(this._lightmapTexture);
  35953. }
  35954. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35955. results.push(this._refractionTexture);
  35956. }
  35957. return results;
  35958. };
  35959. StandardMaterial.prototype.getActiveTextures = function () {
  35960. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35961. if (this._diffuseTexture) {
  35962. activeTextures.push(this._diffuseTexture);
  35963. }
  35964. if (this._ambientTexture) {
  35965. activeTextures.push(this._ambientTexture);
  35966. }
  35967. if (this._opacityTexture) {
  35968. activeTextures.push(this._opacityTexture);
  35969. }
  35970. if (this._reflectionTexture) {
  35971. activeTextures.push(this._reflectionTexture);
  35972. }
  35973. if (this._emissiveTexture) {
  35974. activeTextures.push(this._emissiveTexture);
  35975. }
  35976. if (this._specularTexture) {
  35977. activeTextures.push(this._specularTexture);
  35978. }
  35979. if (this._bumpTexture) {
  35980. activeTextures.push(this._bumpTexture);
  35981. }
  35982. if (this._lightmapTexture) {
  35983. activeTextures.push(this._lightmapTexture);
  35984. }
  35985. if (this._refractionTexture) {
  35986. activeTextures.push(this._refractionTexture);
  35987. }
  35988. return activeTextures;
  35989. };
  35990. StandardMaterial.prototype.hasTexture = function (texture) {
  35991. if (_super.prototype.hasTexture.call(this, texture)) {
  35992. return true;
  35993. }
  35994. if (this._diffuseTexture === texture) {
  35995. return true;
  35996. }
  35997. if (this._ambientTexture === texture) {
  35998. return true;
  35999. }
  36000. if (this._opacityTexture === texture) {
  36001. return true;
  36002. }
  36003. if (this._reflectionTexture === texture) {
  36004. return true;
  36005. }
  36006. if (this._emissiveTexture === texture) {
  36007. return true;
  36008. }
  36009. if (this._specularTexture === texture) {
  36010. return true;
  36011. }
  36012. if (this._bumpTexture === texture) {
  36013. return true;
  36014. }
  36015. if (this._lightmapTexture === texture) {
  36016. return true;
  36017. }
  36018. if (this._refractionTexture === texture) {
  36019. return true;
  36020. }
  36021. return false;
  36022. };
  36023. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36024. if (forceDisposeTextures) {
  36025. if (this._diffuseTexture) {
  36026. this._diffuseTexture.dispose();
  36027. }
  36028. if (this._ambientTexture) {
  36029. this._ambientTexture.dispose();
  36030. }
  36031. if (this._opacityTexture) {
  36032. this._opacityTexture.dispose();
  36033. }
  36034. if (this._reflectionTexture) {
  36035. this._reflectionTexture.dispose();
  36036. }
  36037. if (this._emissiveTexture) {
  36038. this._emissiveTexture.dispose();
  36039. }
  36040. if (this._specularTexture) {
  36041. this._specularTexture.dispose();
  36042. }
  36043. if (this._bumpTexture) {
  36044. this._bumpTexture.dispose();
  36045. }
  36046. if (this._lightmapTexture) {
  36047. this._lightmapTexture.dispose();
  36048. }
  36049. if (this._refractionTexture) {
  36050. this._refractionTexture.dispose();
  36051. }
  36052. }
  36053. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36054. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36055. }
  36056. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36057. };
  36058. StandardMaterial.prototype.clone = function (name) {
  36059. var _this = this;
  36060. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  36061. result.name = name;
  36062. result.id = name;
  36063. return result;
  36064. };
  36065. StandardMaterial.prototype.serialize = function () {
  36066. return BABYLON.SerializationHelper.Serialize(this);
  36067. };
  36068. // Statics
  36069. StandardMaterial.Parse = function (source, scene, rootUrl) {
  36070. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  36071. };
  36072. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  36073. get: function () {
  36074. return StandardMaterial._DiffuseTextureEnabled;
  36075. },
  36076. set: function (value) {
  36077. if (StandardMaterial._DiffuseTextureEnabled === value) {
  36078. return;
  36079. }
  36080. StandardMaterial._DiffuseTextureEnabled = value;
  36081. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36082. },
  36083. enumerable: true,
  36084. configurable: true
  36085. });
  36086. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  36087. get: function () {
  36088. return StandardMaterial._AmbientTextureEnabled;
  36089. },
  36090. set: function (value) {
  36091. if (StandardMaterial._AmbientTextureEnabled === value) {
  36092. return;
  36093. }
  36094. StandardMaterial._AmbientTextureEnabled = value;
  36095. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36096. },
  36097. enumerable: true,
  36098. configurable: true
  36099. });
  36100. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  36101. get: function () {
  36102. return StandardMaterial._OpacityTextureEnabled;
  36103. },
  36104. set: function (value) {
  36105. if (StandardMaterial._OpacityTextureEnabled === value) {
  36106. return;
  36107. }
  36108. StandardMaterial._OpacityTextureEnabled = value;
  36109. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36110. },
  36111. enumerable: true,
  36112. configurable: true
  36113. });
  36114. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  36115. get: function () {
  36116. return StandardMaterial._ReflectionTextureEnabled;
  36117. },
  36118. set: function (value) {
  36119. if (StandardMaterial._ReflectionTextureEnabled === value) {
  36120. return;
  36121. }
  36122. StandardMaterial._ReflectionTextureEnabled = value;
  36123. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36124. },
  36125. enumerable: true,
  36126. configurable: true
  36127. });
  36128. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  36129. get: function () {
  36130. return StandardMaterial._EmissiveTextureEnabled;
  36131. },
  36132. set: function (value) {
  36133. if (StandardMaterial._EmissiveTextureEnabled === value) {
  36134. return;
  36135. }
  36136. StandardMaterial._EmissiveTextureEnabled = value;
  36137. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36138. },
  36139. enumerable: true,
  36140. configurable: true
  36141. });
  36142. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  36143. get: function () {
  36144. return StandardMaterial._SpecularTextureEnabled;
  36145. },
  36146. set: function (value) {
  36147. if (StandardMaterial._SpecularTextureEnabled === value) {
  36148. return;
  36149. }
  36150. StandardMaterial._SpecularTextureEnabled = value;
  36151. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36152. },
  36153. enumerable: true,
  36154. configurable: true
  36155. });
  36156. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  36157. get: function () {
  36158. return StandardMaterial._BumpTextureEnabled;
  36159. },
  36160. set: function (value) {
  36161. if (StandardMaterial._BumpTextureEnabled === value) {
  36162. return;
  36163. }
  36164. StandardMaterial._BumpTextureEnabled = value;
  36165. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36166. },
  36167. enumerable: true,
  36168. configurable: true
  36169. });
  36170. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  36171. get: function () {
  36172. return StandardMaterial._LightmapTextureEnabled;
  36173. },
  36174. set: function (value) {
  36175. if (StandardMaterial._LightmapTextureEnabled === value) {
  36176. return;
  36177. }
  36178. StandardMaterial._LightmapTextureEnabled = value;
  36179. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36180. },
  36181. enumerable: true,
  36182. configurable: true
  36183. });
  36184. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  36185. get: function () {
  36186. return StandardMaterial._RefractionTextureEnabled;
  36187. },
  36188. set: function (value) {
  36189. if (StandardMaterial._RefractionTextureEnabled === value) {
  36190. return;
  36191. }
  36192. StandardMaterial._RefractionTextureEnabled = value;
  36193. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36194. },
  36195. enumerable: true,
  36196. configurable: true
  36197. });
  36198. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  36199. get: function () {
  36200. return StandardMaterial._ColorGradingTextureEnabled;
  36201. },
  36202. set: function (value) {
  36203. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  36204. return;
  36205. }
  36206. StandardMaterial._ColorGradingTextureEnabled = value;
  36207. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36208. },
  36209. enumerable: true,
  36210. configurable: true
  36211. });
  36212. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  36213. get: function () {
  36214. return StandardMaterial._FresnelEnabled;
  36215. },
  36216. set: function (value) {
  36217. if (StandardMaterial._FresnelEnabled === value) {
  36218. return;
  36219. }
  36220. StandardMaterial._FresnelEnabled = value;
  36221. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  36222. },
  36223. enumerable: true,
  36224. configurable: true
  36225. });
  36226. // Flags used to enable or disable a type of texture for all Standard Materials
  36227. StandardMaterial._DiffuseTextureEnabled = true;
  36228. StandardMaterial._AmbientTextureEnabled = true;
  36229. StandardMaterial._OpacityTextureEnabled = true;
  36230. StandardMaterial._ReflectionTextureEnabled = true;
  36231. StandardMaterial._EmissiveTextureEnabled = true;
  36232. StandardMaterial._SpecularTextureEnabled = true;
  36233. StandardMaterial._BumpTextureEnabled = true;
  36234. StandardMaterial._LightmapTextureEnabled = true;
  36235. StandardMaterial._RefractionTextureEnabled = true;
  36236. StandardMaterial._ColorGradingTextureEnabled = true;
  36237. StandardMaterial._FresnelEnabled = true;
  36238. __decorate([
  36239. BABYLON.serializeAsTexture("diffuseTexture")
  36240. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  36241. __decorate([
  36242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36243. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  36244. __decorate([
  36245. BABYLON.serializeAsTexture("ambientTexture")
  36246. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  36247. __decorate([
  36248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36249. ], StandardMaterial.prototype, "ambientTexture", void 0);
  36250. __decorate([
  36251. BABYLON.serializeAsTexture("opacityTexture")
  36252. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  36253. __decorate([
  36254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36255. ], StandardMaterial.prototype, "opacityTexture", void 0);
  36256. __decorate([
  36257. BABYLON.serializeAsTexture("reflectionTexture")
  36258. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  36259. __decorate([
  36260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36261. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  36262. __decorate([
  36263. BABYLON.serializeAsTexture("emissiveTexture")
  36264. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  36265. __decorate([
  36266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36267. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  36268. __decorate([
  36269. BABYLON.serializeAsTexture("specularTexture")
  36270. ], StandardMaterial.prototype, "_specularTexture", void 0);
  36271. __decorate([
  36272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36273. ], StandardMaterial.prototype, "specularTexture", void 0);
  36274. __decorate([
  36275. BABYLON.serializeAsTexture("bumpTexture")
  36276. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  36277. __decorate([
  36278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36279. ], StandardMaterial.prototype, "bumpTexture", void 0);
  36280. __decorate([
  36281. BABYLON.serializeAsTexture("lightmapTexture")
  36282. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  36283. __decorate([
  36284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36285. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  36286. __decorate([
  36287. BABYLON.serializeAsTexture("refractionTexture")
  36288. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  36289. __decorate([
  36290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36291. ], StandardMaterial.prototype, "refractionTexture", void 0);
  36292. __decorate([
  36293. BABYLON.serializeAsColor3("ambient")
  36294. ], StandardMaterial.prototype, "ambientColor", void 0);
  36295. __decorate([
  36296. BABYLON.serializeAsColor3("diffuse")
  36297. ], StandardMaterial.prototype, "diffuseColor", void 0);
  36298. __decorate([
  36299. BABYLON.serializeAsColor3("specular")
  36300. ], StandardMaterial.prototype, "specularColor", void 0);
  36301. __decorate([
  36302. BABYLON.serializeAsColor3("emissive")
  36303. ], StandardMaterial.prototype, "emissiveColor", void 0);
  36304. __decorate([
  36305. BABYLON.serialize()
  36306. ], StandardMaterial.prototype, "specularPower", void 0);
  36307. __decorate([
  36308. BABYLON.serialize("useAlphaFromDiffuseTexture")
  36309. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  36310. __decorate([
  36311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36312. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  36313. __decorate([
  36314. BABYLON.serialize("useEmissiveAsIllumination")
  36315. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  36316. __decorate([
  36317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36318. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  36319. __decorate([
  36320. BABYLON.serialize("linkEmissiveWithDiffuse")
  36321. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  36322. __decorate([
  36323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36324. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  36325. __decorate([
  36326. BABYLON.serialize("useSpecularOverAlpha")
  36327. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  36328. __decorate([
  36329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36330. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  36331. __decorate([
  36332. BABYLON.serialize("useReflectionOverAlpha")
  36333. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  36334. __decorate([
  36335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36336. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  36337. __decorate([
  36338. BABYLON.serialize("disableLighting")
  36339. ], StandardMaterial.prototype, "_disableLighting", void 0);
  36340. __decorate([
  36341. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36342. ], StandardMaterial.prototype, "disableLighting", void 0);
  36343. __decorate([
  36344. BABYLON.serialize("useParallax")
  36345. ], StandardMaterial.prototype, "_useParallax", void 0);
  36346. __decorate([
  36347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36348. ], StandardMaterial.prototype, "useParallax", void 0);
  36349. __decorate([
  36350. BABYLON.serialize("useParallaxOcclusion")
  36351. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  36352. __decorate([
  36353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36354. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  36355. __decorate([
  36356. BABYLON.serialize()
  36357. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  36358. __decorate([
  36359. BABYLON.serialize("roughness")
  36360. ], StandardMaterial.prototype, "_roughness", void 0);
  36361. __decorate([
  36362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36363. ], StandardMaterial.prototype, "roughness", void 0);
  36364. __decorate([
  36365. BABYLON.serialize()
  36366. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  36367. __decorate([
  36368. BABYLON.serialize()
  36369. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  36370. __decorate([
  36371. BABYLON.serialize("useLightmapAsShadowmap")
  36372. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  36373. __decorate([
  36374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36375. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36376. __decorate([
  36377. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  36378. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  36379. __decorate([
  36380. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36381. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  36382. __decorate([
  36383. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  36384. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  36385. __decorate([
  36386. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36387. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  36388. __decorate([
  36389. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  36390. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  36391. __decorate([
  36392. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36393. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  36394. __decorate([
  36395. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  36396. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  36397. __decorate([
  36398. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36399. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  36400. __decorate([
  36401. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  36402. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  36403. __decorate([
  36404. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36405. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  36406. __decorate([
  36407. BABYLON.serialize("useReflectionFresnelFromSpecular")
  36408. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  36409. __decorate([
  36410. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36411. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  36412. __decorate([
  36413. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  36414. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  36415. __decorate([
  36416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36417. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  36418. __decorate([
  36419. BABYLON.serialize("maxSimultaneousLights")
  36420. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  36421. __decorate([
  36422. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36423. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  36424. __decorate([
  36425. BABYLON.serialize("invertNormalMapX")
  36426. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  36427. __decorate([
  36428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36429. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  36430. __decorate([
  36431. BABYLON.serialize("invertNormalMapY")
  36432. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  36433. __decorate([
  36434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36435. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  36436. __decorate([
  36437. BABYLON.serialize("twoSidedLighting")
  36438. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  36439. __decorate([
  36440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36441. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  36442. __decorate([
  36443. BABYLON.serialize()
  36444. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  36445. return StandardMaterial;
  36446. }(BABYLON.PushMaterial));
  36447. BABYLON.StandardMaterial = StandardMaterial;
  36448. })(BABYLON || (BABYLON = {}));
  36449. //# sourceMappingURL=babylon.standardMaterial.js.map
  36450. var BABYLON;
  36451. (function (BABYLON) {
  36452. var PBRMaterialDefines = /** @class */ (function (_super) {
  36453. __extends(PBRMaterialDefines, _super);
  36454. function PBRMaterialDefines() {
  36455. var _this = _super.call(this) || this;
  36456. _this.PBR = true;
  36457. _this.MAINUV1 = false;
  36458. _this.MAINUV2 = false;
  36459. _this.UV1 = false;
  36460. _this.UV2 = false;
  36461. _this.ALBEDO = false;
  36462. _this.ALBEDODIRECTUV = 0;
  36463. _this.VERTEXCOLOR = false;
  36464. _this.AMBIENT = false;
  36465. _this.AMBIENTDIRECTUV = 0;
  36466. _this.AMBIENTINGRAYSCALE = false;
  36467. _this.OPACITY = false;
  36468. _this.VERTEXALPHA = false;
  36469. _this.OPACITYDIRECTUV = 0;
  36470. _this.OPACITYRGB = false;
  36471. _this.ALPHATEST = false;
  36472. _this.DEPTHPREPASS = false;
  36473. _this.ALPHABLEND = false;
  36474. _this.ALPHAFROMALBEDO = false;
  36475. _this.ALPHATESTVALUE = 0.5;
  36476. _this.SPECULAROVERALPHA = false;
  36477. _this.RADIANCEOVERALPHA = false;
  36478. _this.ALPHAFRESNEL = false;
  36479. _this.LINEARALPHAFRESNEL = false;
  36480. _this.PREMULTIPLYALPHA = false;
  36481. _this.EMISSIVE = false;
  36482. _this.EMISSIVEDIRECTUV = 0;
  36483. _this.REFLECTIVITY = false;
  36484. _this.REFLECTIVITYDIRECTUV = 0;
  36485. _this.SPECULARTERM = false;
  36486. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  36487. _this.MICROSURFACEAUTOMATIC = false;
  36488. _this.LODBASEDMICROSFURACE = false;
  36489. _this.MICROSURFACEMAP = false;
  36490. _this.MICROSURFACEMAPDIRECTUV = 0;
  36491. _this.METALLICWORKFLOW = false;
  36492. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  36493. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  36494. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  36495. _this.AOSTOREINMETALMAPRED = false;
  36496. _this.ENVIRONMENTBRDF = false;
  36497. _this.NORMAL = false;
  36498. _this.TANGENT = false;
  36499. _this.BUMP = false;
  36500. _this.BUMPDIRECTUV = 0;
  36501. _this.PARALLAX = false;
  36502. _this.PARALLAXOCCLUSION = false;
  36503. _this.NORMALXYSCALE = true;
  36504. _this.LIGHTMAP = false;
  36505. _this.LIGHTMAPDIRECTUV = 0;
  36506. _this.USELIGHTMAPASSHADOWMAP = false;
  36507. _this.REFLECTION = false;
  36508. _this.REFLECTIONMAP_3D = false;
  36509. _this.REFLECTIONMAP_SPHERICAL = false;
  36510. _this.REFLECTIONMAP_PLANAR = false;
  36511. _this.REFLECTIONMAP_CUBIC = false;
  36512. _this.REFLECTIONMAP_PROJECTION = false;
  36513. _this.REFLECTIONMAP_SKYBOX = false;
  36514. _this.REFLECTIONMAP_EXPLICIT = false;
  36515. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36516. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36517. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36518. _this.INVERTCUBICMAP = false;
  36519. _this.USESPHERICALFROMREFLECTIONMAP = false;
  36520. _this.USESPHERICALINVERTEX = false;
  36521. _this.REFLECTIONMAP_OPPOSITEZ = false;
  36522. _this.LODINREFLECTIONALPHA = false;
  36523. _this.GAMMAREFLECTION = false;
  36524. _this.RADIANCEOCCLUSION = false;
  36525. _this.HORIZONOCCLUSION = false;
  36526. _this.REFRACTION = false;
  36527. _this.REFRACTIONMAP_3D = false;
  36528. _this.REFRACTIONMAP_OPPOSITEZ = false;
  36529. _this.LODINREFRACTIONALPHA = false;
  36530. _this.GAMMAREFRACTION = false;
  36531. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  36532. _this.INSTANCES = false;
  36533. _this.NUM_BONE_INFLUENCERS = 0;
  36534. _this.BonesPerMesh = 0;
  36535. _this.NONUNIFORMSCALING = false;
  36536. _this.MORPHTARGETS = false;
  36537. _this.MORPHTARGETS_NORMAL = false;
  36538. _this.MORPHTARGETS_TANGENT = false;
  36539. _this.NUM_MORPH_INFLUENCERS = 0;
  36540. _this.IMAGEPROCESSING = false;
  36541. _this.VIGNETTE = false;
  36542. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36543. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36544. _this.TONEMAPPING = false;
  36545. _this.CONTRAST = false;
  36546. _this.COLORCURVES = false;
  36547. _this.COLORGRADING = false;
  36548. _this.COLORGRADING3D = false;
  36549. _this.SAMPLER3DGREENDEPTH = false;
  36550. _this.SAMPLER3DBGRMAP = false;
  36551. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36552. _this.EXPOSURE = false;
  36553. _this.USEPHYSICALLIGHTFALLOFF = false;
  36554. _this.TWOSIDEDLIGHTING = false;
  36555. _this.SHADOWFLOAT = false;
  36556. _this.CLIPPLANE = false;
  36557. _this.POINTSIZE = false;
  36558. _this.FOG = false;
  36559. _this.LOGARITHMICDEPTH = false;
  36560. _this.FORCENORMALFORWARD = false;
  36561. _this.rebuild();
  36562. return _this;
  36563. }
  36564. PBRMaterialDefines.prototype.reset = function () {
  36565. _super.prototype.reset.call(this);
  36566. this.ALPHATESTVALUE = 0.5;
  36567. this.PBR = true;
  36568. };
  36569. return PBRMaterialDefines;
  36570. }(BABYLON.MaterialDefines));
  36571. /**
  36572. * The Physically based material base class of BJS.
  36573. *
  36574. * This offers the main features of a standard PBR material.
  36575. * For more information, please refer to the documentation :
  36576. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36577. */
  36578. var PBRBaseMaterial = /** @class */ (function (_super) {
  36579. __extends(PBRBaseMaterial, _super);
  36580. /**
  36581. * Instantiates a new PBRMaterial instance.
  36582. *
  36583. * @param name The material name
  36584. * @param scene The scene the material will be use in.
  36585. */
  36586. function PBRBaseMaterial(name, scene) {
  36587. var _this = _super.call(this, name, scene) || this;
  36588. /**
  36589. * Intensity of the direct lights e.g. the four lights available in your scene.
  36590. * This impacts both the direct diffuse and specular highlights.
  36591. */
  36592. _this._directIntensity = 1.0;
  36593. /**
  36594. * Intensity of the emissive part of the material.
  36595. * This helps controlling the emissive effect without modifying the emissive color.
  36596. */
  36597. _this._emissiveIntensity = 1.0;
  36598. /**
  36599. * Intensity of the environment e.g. how much the environment will light the object
  36600. * either through harmonics for rough material or through the refelction for shiny ones.
  36601. */
  36602. _this._environmentIntensity = 1.0;
  36603. /**
  36604. * This is a special control allowing the reduction of the specular highlights coming from the
  36605. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36606. */
  36607. _this._specularIntensity = 1.0;
  36608. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  36609. /**
  36610. * Debug Control allowing disabling the bump map on this material.
  36611. */
  36612. _this._disableBumpMap = false;
  36613. /**
  36614. * AKA Occlusion Texture Intensity in other nomenclature.
  36615. */
  36616. _this._ambientTextureStrength = 1.0;
  36617. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  36618. /**
  36619. * AKA Diffuse Color in other nomenclature.
  36620. */
  36621. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  36622. /**
  36623. * AKA Specular Color in other nomenclature.
  36624. */
  36625. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36626. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  36627. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  36628. /**
  36629. * AKA Glossiness in other nomenclature.
  36630. */
  36631. _this._microSurface = 0.9;
  36632. /**
  36633. * source material index of refraction (IOR)' / 'destination material IOR.
  36634. */
  36635. _this._indexOfRefraction = 0.66;
  36636. /**
  36637. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36638. */
  36639. _this._invertRefractionY = false;
  36640. /**
  36641. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36642. * Materials half opaque for instance using refraction could benefit from this control.
  36643. */
  36644. _this._linkRefractionWithTransparency = false;
  36645. _this._useLightmapAsShadowmap = false;
  36646. /**
  36647. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  36648. * makes the reflect vector face the model (under horizon).
  36649. */
  36650. _this._useHorizonOcclusion = true;
  36651. /**
  36652. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  36653. * too much the area relying on ambient texture to define their ambient occlusion.
  36654. */
  36655. _this._useRadianceOcclusion = true;
  36656. /**
  36657. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36658. */
  36659. _this._useAlphaFromAlbedoTexture = false;
  36660. /**
  36661. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36662. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36663. */
  36664. _this._useSpecularOverAlpha = true;
  36665. /**
  36666. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36667. */
  36668. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  36669. /**
  36670. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36671. */
  36672. _this._useRoughnessFromMetallicTextureAlpha = true;
  36673. /**
  36674. * Specifies if the metallic texture contains the roughness information in its green channel.
  36675. */
  36676. _this._useRoughnessFromMetallicTextureGreen = false;
  36677. /**
  36678. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36679. */
  36680. _this._useMetallnessFromMetallicTextureBlue = false;
  36681. /**
  36682. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36683. */
  36684. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  36685. /**
  36686. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36687. */
  36688. _this._useAmbientInGrayScale = false;
  36689. /**
  36690. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36691. * The material will try to infer what glossiness each pixel should be.
  36692. */
  36693. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  36694. /**
  36695. * BJS is using an harcoded light falloff based on a manually sets up range.
  36696. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36697. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36698. */
  36699. _this._usePhysicalLightFalloff = true;
  36700. /**
  36701. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36702. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36703. */
  36704. _this._useRadianceOverAlpha = true;
  36705. /**
  36706. * Allows using the bump map in parallax mode.
  36707. */
  36708. _this._useParallax = false;
  36709. /**
  36710. * Allows using the bump map in parallax occlusion mode.
  36711. */
  36712. _this._useParallaxOcclusion = false;
  36713. /**
  36714. * Controls the scale bias of the parallax mode.
  36715. */
  36716. _this._parallaxScaleBias = 0.05;
  36717. /**
  36718. * If sets to true, disables all the lights affecting the material.
  36719. */
  36720. _this._disableLighting = false;
  36721. /**
  36722. * Number of Simultaneous lights allowed on the material.
  36723. */
  36724. _this._maxSimultaneousLights = 4;
  36725. /**
  36726. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  36727. */
  36728. _this._invertNormalMapX = false;
  36729. /**
  36730. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  36731. */
  36732. _this._invertNormalMapY = false;
  36733. /**
  36734. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36735. */
  36736. _this._twoSidedLighting = false;
  36737. /**
  36738. * Defines the alpha limits in alpha test mode.
  36739. */
  36740. _this._alphaCutOff = 0.4;
  36741. /**
  36742. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36743. */
  36744. _this._forceAlphaTest = false;
  36745. /**
  36746. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36747. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  36748. */
  36749. _this._useAlphaFresnel = false;
  36750. /**
  36751. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36752. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  36753. */
  36754. _this._useLinearAlphaFresnel = false;
  36755. /**
  36756. * The transparency mode of the material.
  36757. */
  36758. _this._transparencyMode = null;
  36759. /**
  36760. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  36761. * from cos thetav and roughness:
  36762. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  36763. */
  36764. _this._environmentBRDFTexture = null;
  36765. /**
  36766. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36767. */
  36768. _this._forceIrradianceInFragment = false;
  36769. /**
  36770. * Force normal to face away from face.
  36771. */
  36772. _this._forceNormalForward = false;
  36773. /**
  36774. * Force metallic workflow.
  36775. */
  36776. _this._forceMetallicWorkflow = false;
  36777. _this._renderTargets = new BABYLON.SmartArray(16);
  36778. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36779. // Setup the default processing configuration to the scene.
  36780. _this._attachImageProcessingConfiguration(null);
  36781. _this.getRenderTargetTextures = function () {
  36782. _this._renderTargets.reset();
  36783. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36784. _this._renderTargets.push(_this._reflectionTexture);
  36785. }
  36786. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36787. _this._renderTargets.push(_this._refractionTexture);
  36788. }
  36789. return _this._renderTargets;
  36790. };
  36791. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36792. return _this;
  36793. }
  36794. /**
  36795. * Attaches a new image processing configuration to the PBR Material.
  36796. * @param configuration
  36797. */
  36798. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36799. var _this = this;
  36800. if (configuration === this._imageProcessingConfiguration) {
  36801. return;
  36802. }
  36803. // Detaches observer.
  36804. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36805. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36806. }
  36807. // Pick the scene configuration if needed.
  36808. if (!configuration) {
  36809. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36810. }
  36811. else {
  36812. this._imageProcessingConfiguration = configuration;
  36813. }
  36814. // Attaches observer.
  36815. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36816. _this._markAllSubMeshesAsImageProcessingDirty();
  36817. });
  36818. };
  36819. PBRBaseMaterial.prototype.getClassName = function () {
  36820. return "PBRBaseMaterial";
  36821. };
  36822. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  36823. get: function () {
  36824. return this._useLogarithmicDepth;
  36825. },
  36826. set: function (value) {
  36827. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36828. },
  36829. enumerable: true,
  36830. configurable: true
  36831. });
  36832. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  36833. /**
  36834. * Gets the current transparency mode.
  36835. */
  36836. get: function () {
  36837. return this._transparencyMode;
  36838. },
  36839. /**
  36840. * Sets the transparency mode of the material.
  36841. */
  36842. set: function (value) {
  36843. if (this._transparencyMode === value) {
  36844. return;
  36845. }
  36846. this._transparencyMode = value;
  36847. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  36848. this._markAllSubMeshesAsTexturesDirty();
  36849. },
  36850. enumerable: true,
  36851. configurable: true
  36852. });
  36853. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  36854. /**
  36855. * Returns true if alpha blending should be disabled.
  36856. */
  36857. get: function () {
  36858. return (this._linkRefractionWithTransparency ||
  36859. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  36860. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36861. },
  36862. enumerable: true,
  36863. configurable: true
  36864. });
  36865. /**
  36866. * Specifies whether or not this material should be rendered in alpha blend mode.
  36867. */
  36868. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  36869. if (this._disableAlphaBlending) {
  36870. return false;
  36871. }
  36872. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  36873. };
  36874. /**
  36875. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  36876. */
  36877. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  36878. if (this._disableAlphaBlending) {
  36879. return false;
  36880. }
  36881. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  36882. };
  36883. /**
  36884. * Specifies whether or not this material should be rendered in alpha test mode.
  36885. */
  36886. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  36887. if (this._forceAlphaTest) {
  36888. return true;
  36889. }
  36890. if (this._linkRefractionWithTransparency) {
  36891. return false;
  36892. }
  36893. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36894. };
  36895. /**
  36896. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  36897. */
  36898. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  36899. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36900. };
  36901. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  36902. return this._albedoTexture;
  36903. };
  36904. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36905. var _this = this;
  36906. if (subMesh.effect && this.isFrozen) {
  36907. if (this._wasPreviouslyReady) {
  36908. return true;
  36909. }
  36910. }
  36911. if (!subMesh._materialDefines) {
  36912. subMesh._materialDefines = new PBRMaterialDefines();
  36913. }
  36914. var scene = this.getScene();
  36915. var defines = subMesh._materialDefines;
  36916. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36917. if (defines._renderId === scene.getRenderId()) {
  36918. return true;
  36919. }
  36920. }
  36921. var engine = scene.getEngine();
  36922. // Lights
  36923. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36924. defines._needNormals = true;
  36925. // Textures
  36926. if (defines._areTexturesDirty) {
  36927. defines._needUVs = false;
  36928. if (scene.texturesEnabled) {
  36929. if (scene.getEngine().getCaps().textureLOD) {
  36930. defines.LODBASEDMICROSFURACE = true;
  36931. }
  36932. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36933. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  36934. return false;
  36935. }
  36936. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  36937. }
  36938. else {
  36939. defines.ALBEDO = false;
  36940. }
  36941. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36942. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36943. return false;
  36944. }
  36945. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36946. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  36947. }
  36948. else {
  36949. defines.AMBIENT = false;
  36950. }
  36951. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36952. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36953. return false;
  36954. }
  36955. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36956. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36957. }
  36958. else {
  36959. defines.OPACITY = false;
  36960. }
  36961. var reflectionTexture = this._getReflectionTexture();
  36962. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36963. if (!reflectionTexture.isReadyOrNotBlocking()) {
  36964. return false;
  36965. }
  36966. defines.REFLECTION = true;
  36967. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  36968. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  36969. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  36970. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  36971. defines.INVERTCUBICMAP = true;
  36972. }
  36973. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  36974. switch (reflectionTexture.coordinatesMode) {
  36975. case BABYLON.Texture.CUBIC_MODE:
  36976. case BABYLON.Texture.INVCUBIC_MODE:
  36977. defines.REFLECTIONMAP_CUBIC = true;
  36978. break;
  36979. case BABYLON.Texture.EXPLICIT_MODE:
  36980. defines.REFLECTIONMAP_EXPLICIT = true;
  36981. break;
  36982. case BABYLON.Texture.PLANAR_MODE:
  36983. defines.REFLECTIONMAP_PLANAR = true;
  36984. break;
  36985. case BABYLON.Texture.PROJECTION_MODE:
  36986. defines.REFLECTIONMAP_PROJECTION = true;
  36987. break;
  36988. case BABYLON.Texture.SKYBOX_MODE:
  36989. defines.REFLECTIONMAP_SKYBOX = true;
  36990. break;
  36991. case BABYLON.Texture.SPHERICAL_MODE:
  36992. defines.REFLECTIONMAP_SPHERICAL = true;
  36993. break;
  36994. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  36995. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  36996. break;
  36997. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  36998. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  36999. break;
  37000. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37001. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  37002. break;
  37003. }
  37004. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  37005. if (reflectionTexture.sphericalPolynomial) {
  37006. defines.USESPHERICALFROMREFLECTIONMAP = true;
  37007. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  37008. defines.USESPHERICALINVERTEX = false;
  37009. }
  37010. else {
  37011. defines.USESPHERICALINVERTEX = true;
  37012. }
  37013. }
  37014. }
  37015. }
  37016. else {
  37017. defines.REFLECTION = false;
  37018. defines.REFLECTIONMAP_3D = false;
  37019. defines.REFLECTIONMAP_SPHERICAL = false;
  37020. defines.REFLECTIONMAP_PLANAR = false;
  37021. defines.REFLECTIONMAP_CUBIC = false;
  37022. defines.REFLECTIONMAP_PROJECTION = false;
  37023. defines.REFLECTIONMAP_SKYBOX = false;
  37024. defines.REFLECTIONMAP_EXPLICIT = false;
  37025. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37026. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37027. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37028. defines.INVERTCUBICMAP = false;
  37029. defines.USESPHERICALFROMREFLECTIONMAP = false;
  37030. defines.USESPHERICALINVERTEX = false;
  37031. defines.REFLECTIONMAP_OPPOSITEZ = false;
  37032. defines.LODINREFLECTIONALPHA = false;
  37033. defines.GAMMAREFLECTION = false;
  37034. }
  37035. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37036. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37037. return false;
  37038. }
  37039. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37040. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37041. }
  37042. else {
  37043. defines.LIGHTMAP = false;
  37044. }
  37045. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37046. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37047. return false;
  37048. }
  37049. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37050. }
  37051. else {
  37052. defines.EMISSIVE = false;
  37053. }
  37054. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37055. if (this._metallicTexture) {
  37056. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  37057. return false;
  37058. }
  37059. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  37060. defines.METALLICWORKFLOW = true;
  37061. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  37062. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  37063. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  37064. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  37065. }
  37066. else if (this._reflectivityTexture) {
  37067. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  37068. return false;
  37069. }
  37070. defines.METALLICWORKFLOW = false;
  37071. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  37072. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  37073. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  37074. }
  37075. else {
  37076. defines.METALLICWORKFLOW = false;
  37077. defines.REFLECTIVITY = false;
  37078. }
  37079. if (this._microSurfaceTexture) {
  37080. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  37081. return false;
  37082. }
  37083. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  37084. }
  37085. else {
  37086. defines.MICROSURFACEMAP = false;
  37087. }
  37088. }
  37089. else {
  37090. defines.REFLECTIVITY = false;
  37091. defines.MICROSURFACEMAP = false;
  37092. }
  37093. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37094. // Bump texure can not be none blocking.
  37095. if (!this._bumpTexture.isReady()) {
  37096. return false;
  37097. }
  37098. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37099. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37100. defines.PARALLAX = true;
  37101. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  37102. }
  37103. else {
  37104. defines.PARALLAX = false;
  37105. }
  37106. }
  37107. else {
  37108. defines.BUMP = false;
  37109. }
  37110. var refractionTexture = this._getRefractionTexture();
  37111. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37112. if (!refractionTexture.isReadyOrNotBlocking()) {
  37113. return false;
  37114. }
  37115. defines.REFRACTION = true;
  37116. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  37117. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  37118. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  37119. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  37120. if (this._linkRefractionWithTransparency) {
  37121. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  37122. }
  37123. }
  37124. else {
  37125. defines.REFRACTION = false;
  37126. }
  37127. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37128. // This is blocking.
  37129. if (!this._environmentBRDFTexture.isReady()) {
  37130. return false;
  37131. }
  37132. defines.ENVIRONMENTBRDF = true;
  37133. }
  37134. else {
  37135. defines.ENVIRONMENTBRDF = false;
  37136. }
  37137. if (this._shouldUseAlphaFromAlbedoTexture()) {
  37138. defines.ALPHAFROMALBEDO = true;
  37139. }
  37140. else {
  37141. defines.ALPHAFROMALBEDO = false;
  37142. }
  37143. }
  37144. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  37145. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  37146. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  37147. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  37148. defines.METALLICWORKFLOW = true;
  37149. }
  37150. else {
  37151. defines.METALLICWORKFLOW = false;
  37152. }
  37153. if (!this.backFaceCulling && this._twoSidedLighting) {
  37154. defines.TWOSIDEDLIGHTING = true;
  37155. }
  37156. else {
  37157. defines.TWOSIDEDLIGHTING = false;
  37158. }
  37159. defines.ALPHATESTVALUE = this._alphaCutOff;
  37160. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  37161. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  37162. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  37163. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  37164. }
  37165. if (defines._areImageProcessingDirty) {
  37166. if (!this._imageProcessingConfiguration.isReady()) {
  37167. return false;
  37168. }
  37169. this._imageProcessingConfiguration.prepareDefines(defines);
  37170. }
  37171. defines.FORCENORMALFORWARD = this._forceNormalForward;
  37172. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  37173. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  37174. // Misc.
  37175. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  37176. // Values that need to be evaluated on every frame
  37177. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  37178. // Attribs
  37179. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  37180. var bufferMesh = null;
  37181. if (mesh instanceof BABYLON.InstancedMesh) {
  37182. bufferMesh = mesh.sourceMesh;
  37183. }
  37184. else if (mesh instanceof BABYLON.Mesh) {
  37185. bufferMesh = mesh;
  37186. }
  37187. if (bufferMesh) {
  37188. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37189. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  37190. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  37191. var normals = normalVertexBuffer.getData();
  37192. var vertexBufferOffset = normalVertexBuffer.getOffset();
  37193. var strideSize = normalVertexBuffer.getStrideSize();
  37194. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  37195. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  37196. defines.NORMAL = false;
  37197. }
  37198. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37199. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  37200. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  37201. var tangents = tangentVertexBuffer.getData();
  37202. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  37203. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  37204. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  37205. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  37206. defines.TANGENT = false;
  37207. }
  37208. }
  37209. }
  37210. else {
  37211. if (!scene.getEngine().getCaps().standardDerivatives) {
  37212. bufferMesh.createNormals(true);
  37213. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  37214. }
  37215. }
  37216. }
  37217. }
  37218. // Get correct effect
  37219. if (defines.isDirty) {
  37220. defines.markAsProcessed();
  37221. scene.resetCachedMaterial();
  37222. // Fallbacks
  37223. var fallbacks = new BABYLON.EffectFallbacks();
  37224. var fallbackRank = 0;
  37225. if (defines.USESPHERICALINVERTEX) {
  37226. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  37227. }
  37228. if (defines.FOG) {
  37229. fallbacks.addFallback(fallbackRank, "FOG");
  37230. }
  37231. if (defines.POINTSIZE) {
  37232. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  37233. }
  37234. if (defines.LOGARITHMICDEPTH) {
  37235. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  37236. }
  37237. if (defines.PARALLAX) {
  37238. fallbacks.addFallback(fallbackRank, "PARALLAX");
  37239. }
  37240. if (defines.PARALLAXOCCLUSION) {
  37241. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  37242. }
  37243. if (defines.ENVIRONMENTBRDF) {
  37244. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  37245. }
  37246. if (defines.TANGENT) {
  37247. fallbacks.addFallback(fallbackRank++, "TANGENT");
  37248. }
  37249. if (defines.BUMP) {
  37250. fallbacks.addFallback(fallbackRank++, "BUMP");
  37251. }
  37252. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  37253. if (defines.SPECULARTERM) {
  37254. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  37255. }
  37256. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  37257. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  37258. }
  37259. if (defines.LIGHTMAP) {
  37260. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  37261. }
  37262. if (defines.NORMAL) {
  37263. fallbacks.addFallback(fallbackRank++, "NORMAL");
  37264. }
  37265. if (defines.AMBIENT) {
  37266. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  37267. }
  37268. if (defines.EMISSIVE) {
  37269. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  37270. }
  37271. if (defines.VERTEXCOLOR) {
  37272. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  37273. }
  37274. if (defines.NUM_BONE_INFLUENCERS > 0) {
  37275. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  37276. }
  37277. if (defines.MORPHTARGETS) {
  37278. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  37279. }
  37280. //Attributes
  37281. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37282. if (defines.NORMAL) {
  37283. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37284. }
  37285. if (defines.TANGENT) {
  37286. attribs.push(BABYLON.VertexBuffer.TangentKind);
  37287. }
  37288. if (defines.UV1) {
  37289. attribs.push(BABYLON.VertexBuffer.UVKind);
  37290. }
  37291. if (defines.UV2) {
  37292. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37293. }
  37294. if (defines.VERTEXCOLOR) {
  37295. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37296. }
  37297. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37298. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37299. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37300. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  37301. "vFogInfos", "vFogColor", "pointSize",
  37302. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37303. "mBones",
  37304. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37305. "vLightingIntensity",
  37306. "logarithmicDepthConstant",
  37307. "vSphericalX", "vSphericalY", "vSphericalZ",
  37308. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  37309. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  37310. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  37311. "vTangentSpaceParams"
  37312. ];
  37313. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  37314. "bumpSampler", "lightmapSampler", "opacitySampler",
  37315. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  37316. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  37317. "microSurfaceSampler", "environmentBrdfSampler"];
  37318. var uniformBuffers = ["Material", "Scene"];
  37319. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37320. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37321. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37322. uniformsNames: uniforms,
  37323. uniformBuffersNames: uniformBuffers,
  37324. samplers: samplers,
  37325. defines: defines,
  37326. maxSimultaneousLights: this._maxSimultaneousLights
  37327. });
  37328. var onCompiled = function (effect) {
  37329. if (_this.onCompiled) {
  37330. _this.onCompiled(effect);
  37331. }
  37332. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  37333. };
  37334. var join = defines.toString();
  37335. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  37336. attributes: attribs,
  37337. uniformsNames: uniforms,
  37338. uniformBuffersNames: uniformBuffers,
  37339. samplers: samplers,
  37340. defines: join,
  37341. fallbacks: fallbacks,
  37342. onCompiled: onCompiled,
  37343. onError: this.onError,
  37344. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37345. }, engine), defines);
  37346. this.buildUniformLayout();
  37347. }
  37348. if (!subMesh.effect || !subMesh.effect.isReady()) {
  37349. return false;
  37350. }
  37351. defines._renderId = scene.getRenderId();
  37352. this._wasPreviouslyReady = true;
  37353. return true;
  37354. };
  37355. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  37356. // Order is important !
  37357. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  37358. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  37359. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37360. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37361. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37362. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  37363. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  37364. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37365. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37366. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37367. this._uniformBuffer.addUniform("albedoMatrix", 16);
  37368. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37369. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37370. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37371. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37372. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  37373. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  37374. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37375. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  37376. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37377. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37378. this._uniformBuffer.addUniform("vReflectionColor", 3);
  37379. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  37380. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  37381. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  37382. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  37383. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  37384. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37385. this._uniformBuffer.addUniform("pointSize", 1);
  37386. this._uniformBuffer.create();
  37387. };
  37388. PBRBaseMaterial.prototype.unbind = function () {
  37389. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37390. this._uniformBuffer.setTexture("reflectionSampler", null);
  37391. }
  37392. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37393. this._uniformBuffer.setTexture("refractionSampler", null);
  37394. }
  37395. _super.prototype.unbind.call(this);
  37396. };
  37397. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37398. this._activeEffect.setMatrix("world", world);
  37399. };
  37400. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37401. var scene = this.getScene();
  37402. var defines = subMesh._materialDefines;
  37403. if (!defines) {
  37404. return;
  37405. }
  37406. var effect = subMesh.effect;
  37407. if (!effect) {
  37408. return;
  37409. }
  37410. this._activeEffect = effect;
  37411. // Matrices
  37412. this.bindOnlyWorldMatrix(world);
  37413. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37414. // Bones
  37415. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  37416. var reflectionTexture = null;
  37417. if (mustRebind) {
  37418. this._uniformBuffer.bindToEffect(effect, "Material");
  37419. this.bindViewProjection(effect);
  37420. reflectionTexture = this._getReflectionTexture();
  37421. var refractionTexture = this._getRefractionTexture();
  37422. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37423. // Texture uniforms
  37424. if (scene.texturesEnabled) {
  37425. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37426. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  37427. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  37428. }
  37429. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37430. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  37431. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37432. }
  37433. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37434. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37435. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37436. }
  37437. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37438. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  37439. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  37440. var polynomials = reflectionTexture.sphericalPolynomial;
  37441. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  37442. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  37443. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  37444. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  37445. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  37446. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  37447. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  37448. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  37449. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  37450. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  37451. }
  37452. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  37453. }
  37454. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37455. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37456. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37457. }
  37458. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37459. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37460. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37461. }
  37462. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37463. if (this._metallicTexture) {
  37464. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  37465. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  37466. }
  37467. else if (this._reflectivityTexture) {
  37468. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  37469. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  37470. }
  37471. if (this._microSurfaceTexture) {
  37472. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  37473. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  37474. }
  37475. }
  37476. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37477. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  37478. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37479. if (scene._mirroredCameraPosition) {
  37480. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37481. }
  37482. else {
  37483. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37484. }
  37485. }
  37486. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37487. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  37488. var depth = 1.0;
  37489. if (!refractionTexture.isCube) {
  37490. if (refractionTexture.depth) {
  37491. depth = refractionTexture.depth;
  37492. }
  37493. }
  37494. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  37495. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  37496. }
  37497. }
  37498. // Point size
  37499. if (this.pointsCloud) {
  37500. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37501. }
  37502. // Colors
  37503. if (defines.METALLICWORKFLOW) {
  37504. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  37505. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  37506. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  37507. }
  37508. else {
  37509. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  37510. }
  37511. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  37512. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  37513. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  37514. // Misc
  37515. this._lightingInfos.x = this._directIntensity;
  37516. this._lightingInfos.y = this._emissiveIntensity;
  37517. this._lightingInfos.z = this._environmentIntensity;
  37518. this._lightingInfos.w = this._specularIntensity;
  37519. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  37520. }
  37521. // Textures
  37522. if (scene.texturesEnabled) {
  37523. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37524. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  37525. }
  37526. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37527. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  37528. }
  37529. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37530. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  37531. }
  37532. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37533. if (defines.LODBASEDMICROSFURACE) {
  37534. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  37535. }
  37536. else {
  37537. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  37538. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  37539. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  37540. }
  37541. }
  37542. if (defines.ENVIRONMENTBRDF) {
  37543. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  37544. }
  37545. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37546. if (defines.LODBASEDMICROSFURACE) {
  37547. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  37548. }
  37549. else {
  37550. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  37551. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  37552. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  37553. }
  37554. }
  37555. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37556. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  37557. }
  37558. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37559. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  37560. }
  37561. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37562. if (this._metallicTexture) {
  37563. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  37564. }
  37565. else if (this._reflectivityTexture) {
  37566. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  37567. }
  37568. if (this._microSurfaceTexture) {
  37569. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  37570. }
  37571. }
  37572. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37573. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  37574. }
  37575. }
  37576. // Clip plane
  37577. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  37578. // Colors
  37579. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  37580. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37581. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  37582. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  37583. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37584. }
  37585. if (mustRebind || !this.isFrozen) {
  37586. // Lights
  37587. if (scene.lightsEnabled && !this._disableLighting) {
  37588. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  37589. }
  37590. // View
  37591. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  37592. this.bindView(effect);
  37593. }
  37594. // Fog
  37595. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  37596. // Morph targets
  37597. if (defines.NUM_MORPH_INFLUENCERS) {
  37598. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  37599. }
  37600. // image processing
  37601. this._imageProcessingConfiguration.bind(this._activeEffect);
  37602. // Log. depth
  37603. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  37604. }
  37605. this._uniformBuffer.update();
  37606. this._afterBind(mesh);
  37607. };
  37608. PBRBaseMaterial.prototype.getAnimatables = function () {
  37609. var results = [];
  37610. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  37611. results.push(this._albedoTexture);
  37612. }
  37613. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37614. results.push(this._ambientTexture);
  37615. }
  37616. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37617. results.push(this._opacityTexture);
  37618. }
  37619. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37620. results.push(this._reflectionTexture);
  37621. }
  37622. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37623. results.push(this._emissiveTexture);
  37624. }
  37625. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  37626. results.push(this._metallicTexture);
  37627. }
  37628. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  37629. results.push(this._reflectivityTexture);
  37630. }
  37631. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37632. results.push(this._bumpTexture);
  37633. }
  37634. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37635. results.push(this._lightmapTexture);
  37636. }
  37637. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37638. results.push(this._refractionTexture);
  37639. }
  37640. return results;
  37641. };
  37642. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  37643. if (this._reflectionTexture) {
  37644. return this._reflectionTexture;
  37645. }
  37646. return this.getScene().environmentTexture;
  37647. };
  37648. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  37649. if (this._refractionTexture) {
  37650. return this._refractionTexture;
  37651. }
  37652. if (this._linkRefractionWithTransparency) {
  37653. return this.getScene().environmentTexture;
  37654. }
  37655. return null;
  37656. };
  37657. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37658. if (forceDisposeTextures) {
  37659. if (this._albedoTexture) {
  37660. this._albedoTexture.dispose();
  37661. }
  37662. if (this._ambientTexture) {
  37663. this._ambientTexture.dispose();
  37664. }
  37665. if (this._opacityTexture) {
  37666. this._opacityTexture.dispose();
  37667. }
  37668. if (this._reflectionTexture) {
  37669. this._reflectionTexture.dispose();
  37670. }
  37671. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  37672. this._environmentBRDFTexture.dispose();
  37673. }
  37674. if (this._emissiveTexture) {
  37675. this._emissiveTexture.dispose();
  37676. }
  37677. if (this._metallicTexture) {
  37678. this._metallicTexture.dispose();
  37679. }
  37680. if (this._reflectivityTexture) {
  37681. this._reflectivityTexture.dispose();
  37682. }
  37683. if (this._bumpTexture) {
  37684. this._bumpTexture.dispose();
  37685. }
  37686. if (this._lightmapTexture) {
  37687. this._lightmapTexture.dispose();
  37688. }
  37689. if (this._refractionTexture) {
  37690. this._refractionTexture.dispose();
  37691. }
  37692. }
  37693. this._renderTargets.dispose();
  37694. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37695. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37696. }
  37697. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37698. };
  37699. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  37700. __decorate([
  37701. BABYLON.serializeAsImageProcessingConfiguration()
  37702. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  37703. __decorate([
  37704. BABYLON.serialize()
  37705. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  37706. __decorate([
  37707. BABYLON.serialize()
  37708. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  37709. return PBRBaseMaterial;
  37710. }(BABYLON.PushMaterial));
  37711. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  37712. })(BABYLON || (BABYLON = {}));
  37713. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  37714. var BABYLON;
  37715. (function (BABYLON) {
  37716. /**
  37717. * The Physically based simple base material of BJS.
  37718. *
  37719. * This enables better naming and convention enforcements on top of the pbrMaterial.
  37720. * It is used as the base class for both the specGloss and metalRough conventions.
  37721. */
  37722. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  37723. __extends(PBRBaseSimpleMaterial, _super);
  37724. /**
  37725. * Instantiates a new PBRMaterial instance.
  37726. *
  37727. * @param name The material name
  37728. * @param scene The scene the material will be use in.
  37729. */
  37730. function PBRBaseSimpleMaterial(name, scene) {
  37731. var _this = _super.call(this, name, scene) || this;
  37732. /**
  37733. * Number of Simultaneous lights allowed on the material.
  37734. */
  37735. _this.maxSimultaneousLights = 4;
  37736. /**
  37737. * If sets to true, disables all the lights affecting the material.
  37738. */
  37739. _this.disableLighting = false;
  37740. /**
  37741. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37742. */
  37743. _this.invertNormalMapX = false;
  37744. /**
  37745. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37746. */
  37747. _this.invertNormalMapY = false;
  37748. /**
  37749. * Emissivie color used to self-illuminate the model.
  37750. */
  37751. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37752. /**
  37753. * Occlusion Channel Strenght.
  37754. */
  37755. _this.occlusionStrength = 1.0;
  37756. _this.useLightmapAsShadowmap = false;
  37757. _this._useAlphaFromAlbedoTexture = true;
  37758. _this._useAmbientInGrayScale = true;
  37759. return _this;
  37760. }
  37761. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  37762. /**
  37763. * Gets the current double sided mode.
  37764. */
  37765. get: function () {
  37766. return this._twoSidedLighting;
  37767. },
  37768. /**
  37769. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37770. */
  37771. set: function (value) {
  37772. if (this._twoSidedLighting === value) {
  37773. return;
  37774. }
  37775. this._twoSidedLighting = value;
  37776. this.backFaceCulling = !value;
  37777. this._markAllSubMeshesAsTexturesDirty();
  37778. },
  37779. enumerable: true,
  37780. configurable: true
  37781. });
  37782. /**
  37783. * Return the active textures of the material.
  37784. */
  37785. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  37786. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37787. if (this.environmentTexture) {
  37788. activeTextures.push(this.environmentTexture);
  37789. }
  37790. if (this.normalTexture) {
  37791. activeTextures.push(this.normalTexture);
  37792. }
  37793. if (this.emissiveTexture) {
  37794. activeTextures.push(this.emissiveTexture);
  37795. }
  37796. if (this.occlusionTexture) {
  37797. activeTextures.push(this.occlusionTexture);
  37798. }
  37799. if (this.lightmapTexture) {
  37800. activeTextures.push(this.lightmapTexture);
  37801. }
  37802. return activeTextures;
  37803. };
  37804. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  37805. if (_super.prototype.hasTexture.call(this, texture)) {
  37806. return true;
  37807. }
  37808. if (this.lightmapTexture === texture) {
  37809. return true;
  37810. }
  37811. return false;
  37812. };
  37813. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  37814. return "PBRBaseSimpleMaterial";
  37815. };
  37816. __decorate([
  37817. BABYLON.serialize(),
  37818. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37819. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  37820. __decorate([
  37821. BABYLON.serialize(),
  37822. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37823. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  37824. __decorate([
  37825. BABYLON.serializeAsTexture(),
  37826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  37827. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  37828. __decorate([
  37829. BABYLON.serialize(),
  37830. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37831. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  37832. __decorate([
  37833. BABYLON.serialize(),
  37834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37835. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  37836. __decorate([
  37837. BABYLON.serializeAsTexture(),
  37838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  37839. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  37840. __decorate([
  37841. BABYLON.serializeAsColor3("emissive"),
  37842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37843. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  37844. __decorate([
  37845. BABYLON.serializeAsTexture(),
  37846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37847. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  37848. __decorate([
  37849. BABYLON.serialize(),
  37850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  37851. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  37852. __decorate([
  37853. BABYLON.serializeAsTexture(),
  37854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  37855. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  37856. __decorate([
  37857. BABYLON.serialize(),
  37858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  37859. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  37860. __decorate([
  37861. BABYLON.serialize()
  37862. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  37863. __decorate([
  37864. BABYLON.serializeAsTexture(),
  37865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37866. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  37867. __decorate([
  37868. BABYLON.serialize(),
  37869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37870. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37871. return PBRBaseSimpleMaterial;
  37872. }(BABYLON.PBRBaseMaterial));
  37873. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  37874. })(BABYLON || (BABYLON = {}));
  37875. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  37876. var BABYLON;
  37877. (function (BABYLON) {
  37878. /**
  37879. * The Physically based material of BJS.
  37880. *
  37881. * This offers the main features of a standard PBR material.
  37882. * For more information, please refer to the documentation :
  37883. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37884. */
  37885. var PBRMaterial = /** @class */ (function (_super) {
  37886. __extends(PBRMaterial, _super);
  37887. /**
  37888. * Instantiates a new PBRMaterial instance.
  37889. *
  37890. * @param name The material name
  37891. * @param scene The scene the material will be use in.
  37892. */
  37893. function PBRMaterial(name, scene) {
  37894. var _this = _super.call(this, name, scene) || this;
  37895. /**
  37896. * Intensity of the direct lights e.g. the four lights available in your scene.
  37897. * This impacts both the direct diffuse and specular highlights.
  37898. */
  37899. _this.directIntensity = 1.0;
  37900. /**
  37901. * Intensity of the emissive part of the material.
  37902. * This helps controlling the emissive effect without modifying the emissive color.
  37903. */
  37904. _this.emissiveIntensity = 1.0;
  37905. /**
  37906. * Intensity of the environment e.g. how much the environment will light the object
  37907. * either through harmonics for rough material or through the refelction for shiny ones.
  37908. */
  37909. _this.environmentIntensity = 1.0;
  37910. /**
  37911. * This is a special control allowing the reduction of the specular highlights coming from the
  37912. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37913. */
  37914. _this.specularIntensity = 1.0;
  37915. /**
  37916. * Debug Control allowing disabling the bump map on this material.
  37917. */
  37918. _this.disableBumpMap = false;
  37919. /**
  37920. * AKA Occlusion Texture Intensity in other nomenclature.
  37921. */
  37922. _this.ambientTextureStrength = 1.0;
  37923. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  37924. /**
  37925. * AKA Diffuse Color in other nomenclature.
  37926. */
  37927. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  37928. /**
  37929. * AKA Specular Color in other nomenclature.
  37930. */
  37931. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37932. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  37933. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37934. /**
  37935. * AKA Glossiness in other nomenclature.
  37936. */
  37937. _this.microSurface = 1.0;
  37938. /**
  37939. * source material index of refraction (IOR)' / 'destination material IOR.
  37940. */
  37941. _this.indexOfRefraction = 0.66;
  37942. /**
  37943. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37944. */
  37945. _this.invertRefractionY = false;
  37946. /**
  37947. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37948. * Materials half opaque for instance using refraction could benefit from this control.
  37949. */
  37950. _this.linkRefractionWithTransparency = false;
  37951. _this.useLightmapAsShadowmap = false;
  37952. /**
  37953. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37954. */
  37955. _this.useAlphaFromAlbedoTexture = false;
  37956. /**
  37957. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37958. */
  37959. _this.forceAlphaTest = false;
  37960. /**
  37961. * Defines the alpha limits in alpha test mode.
  37962. */
  37963. _this.alphaCutOff = 0.4;
  37964. /**
  37965. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37966. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37967. */
  37968. _this.useSpecularOverAlpha = true;
  37969. /**
  37970. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37971. */
  37972. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  37973. /**
  37974. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37975. */
  37976. _this.useRoughnessFromMetallicTextureAlpha = true;
  37977. /**
  37978. * Specifies if the metallic texture contains the roughness information in its green channel.
  37979. */
  37980. _this.useRoughnessFromMetallicTextureGreen = false;
  37981. /**
  37982. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37983. */
  37984. _this.useMetallnessFromMetallicTextureBlue = false;
  37985. /**
  37986. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37987. */
  37988. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  37989. /**
  37990. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37991. */
  37992. _this.useAmbientInGrayScale = false;
  37993. /**
  37994. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37995. * The material will try to infer what glossiness each pixel should be.
  37996. */
  37997. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  37998. /**
  37999. * BJS is using an harcoded light falloff based on a manually sets up range.
  38000. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38001. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38002. */
  38003. _this.usePhysicalLightFalloff = true;
  38004. /**
  38005. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38006. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38007. */
  38008. _this.useRadianceOverAlpha = true;
  38009. /**
  38010. * Allows using the bump map in parallax mode.
  38011. */
  38012. _this.useParallax = false;
  38013. /**
  38014. * Allows using the bump map in parallax occlusion mode.
  38015. */
  38016. _this.useParallaxOcclusion = false;
  38017. /**
  38018. * Controls the scale bias of the parallax mode.
  38019. */
  38020. _this.parallaxScaleBias = 0.05;
  38021. /**
  38022. * If sets to true, disables all the lights affecting the material.
  38023. */
  38024. _this.disableLighting = false;
  38025. /**
  38026. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38027. */
  38028. _this.forceIrradianceInFragment = false;
  38029. /**
  38030. * Number of Simultaneous lights allowed on the material.
  38031. */
  38032. _this.maxSimultaneousLights = 4;
  38033. /**
  38034. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38035. */
  38036. _this.invertNormalMapX = false;
  38037. /**
  38038. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38039. */
  38040. _this.invertNormalMapY = false;
  38041. /**
  38042. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38043. */
  38044. _this.twoSidedLighting = false;
  38045. /**
  38046. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38047. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  38048. */
  38049. _this.useAlphaFresnel = false;
  38050. /**
  38051. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38052. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  38053. */
  38054. _this.useLinearAlphaFresnel = false;
  38055. /**
  38056. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38057. * And/Or occlude the blended part.
  38058. */
  38059. _this.environmentBRDFTexture = null;
  38060. /**
  38061. * Force normal to face away from face.
  38062. */
  38063. _this.forceNormalForward = false;
  38064. /**
  38065. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  38066. * makes the reflect vector face the model (under horizon).
  38067. */
  38068. _this.useHorizonOcclusion = true;
  38069. /**
  38070. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  38071. * too much the area relying on ambient texture to define their ambient occlusion.
  38072. */
  38073. _this.useRadianceOcclusion = true;
  38074. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38075. return _this;
  38076. }
  38077. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  38078. /**
  38079. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  38080. */
  38081. get: function () {
  38082. return this._PBRMATERIAL_OPAQUE;
  38083. },
  38084. enumerable: true,
  38085. configurable: true
  38086. });
  38087. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  38088. /**
  38089. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  38090. */
  38091. get: function () {
  38092. return this._PBRMATERIAL_ALPHATEST;
  38093. },
  38094. enumerable: true,
  38095. configurable: true
  38096. });
  38097. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  38098. /**
  38099. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38100. */
  38101. get: function () {
  38102. return this._PBRMATERIAL_ALPHABLEND;
  38103. },
  38104. enumerable: true,
  38105. configurable: true
  38106. });
  38107. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  38108. /**
  38109. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38110. * They are also discarded below the alpha cutoff threshold to improve performances.
  38111. */
  38112. get: function () {
  38113. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  38114. },
  38115. enumerable: true,
  38116. configurable: true
  38117. });
  38118. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  38119. /**
  38120. * Gets the image processing configuration used either in this material.
  38121. */
  38122. get: function () {
  38123. return this._imageProcessingConfiguration;
  38124. },
  38125. /**
  38126. * Sets the Default image processing configuration used either in the this material.
  38127. *
  38128. * If sets to null, the scene one is in use.
  38129. */
  38130. set: function (value) {
  38131. this._attachImageProcessingConfiguration(value);
  38132. // Ensure the effect will be rebuilt.
  38133. this._markAllSubMeshesAsTexturesDirty();
  38134. },
  38135. enumerable: true,
  38136. configurable: true
  38137. });
  38138. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  38139. /**
  38140. * Gets wether the color curves effect is enabled.
  38141. */
  38142. get: function () {
  38143. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38144. },
  38145. /**
  38146. * Sets wether the color curves effect is enabled.
  38147. */
  38148. set: function (value) {
  38149. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38150. },
  38151. enumerable: true,
  38152. configurable: true
  38153. });
  38154. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  38155. /**
  38156. * Gets wether the color grading effect is enabled.
  38157. */
  38158. get: function () {
  38159. return this.imageProcessingConfiguration.colorGradingEnabled;
  38160. },
  38161. /**
  38162. * Gets wether the color grading effect is enabled.
  38163. */
  38164. set: function (value) {
  38165. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38166. },
  38167. enumerable: true,
  38168. configurable: true
  38169. });
  38170. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  38171. /**
  38172. * Gets wether tonemapping is enabled or not.
  38173. */
  38174. get: function () {
  38175. return this._imageProcessingConfiguration.toneMappingEnabled;
  38176. },
  38177. /**
  38178. * Sets wether tonemapping is enabled or not
  38179. */
  38180. set: function (value) {
  38181. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38182. },
  38183. enumerable: true,
  38184. configurable: true
  38185. });
  38186. ;
  38187. ;
  38188. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  38189. /**
  38190. * The camera exposure used on this material.
  38191. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38192. * This corresponds to a photographic exposure.
  38193. */
  38194. get: function () {
  38195. return this._imageProcessingConfiguration.exposure;
  38196. },
  38197. /**
  38198. * The camera exposure used on this material.
  38199. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38200. * This corresponds to a photographic exposure.
  38201. */
  38202. set: function (value) {
  38203. this._imageProcessingConfiguration.exposure = value;
  38204. },
  38205. enumerable: true,
  38206. configurable: true
  38207. });
  38208. ;
  38209. ;
  38210. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  38211. /**
  38212. * Gets The camera contrast used on this material.
  38213. */
  38214. get: function () {
  38215. return this._imageProcessingConfiguration.contrast;
  38216. },
  38217. /**
  38218. * Sets The camera contrast used on this material.
  38219. */
  38220. set: function (value) {
  38221. this._imageProcessingConfiguration.contrast = value;
  38222. },
  38223. enumerable: true,
  38224. configurable: true
  38225. });
  38226. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  38227. /**
  38228. * Gets the Color Grading 2D Lookup Texture.
  38229. */
  38230. get: function () {
  38231. return this._imageProcessingConfiguration.colorGradingTexture;
  38232. },
  38233. /**
  38234. * Sets the Color Grading 2D Lookup Texture.
  38235. */
  38236. set: function (value) {
  38237. this._imageProcessingConfiguration.colorGradingTexture = value;
  38238. },
  38239. enumerable: true,
  38240. configurable: true
  38241. });
  38242. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  38243. /**
  38244. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38245. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38246. * 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;
  38247. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38248. */
  38249. get: function () {
  38250. return this._imageProcessingConfiguration.colorCurves;
  38251. },
  38252. /**
  38253. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38254. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38255. * 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;
  38256. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38257. */
  38258. set: function (value) {
  38259. this._imageProcessingConfiguration.colorCurves = value;
  38260. },
  38261. enumerable: true,
  38262. configurable: true
  38263. });
  38264. PBRMaterial.prototype.getClassName = function () {
  38265. return "PBRMaterial";
  38266. };
  38267. PBRMaterial.prototype.getActiveTextures = function () {
  38268. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38269. if (this._albedoTexture) {
  38270. activeTextures.push(this._albedoTexture);
  38271. }
  38272. if (this._ambientTexture) {
  38273. activeTextures.push(this._ambientTexture);
  38274. }
  38275. if (this._opacityTexture) {
  38276. activeTextures.push(this._opacityTexture);
  38277. }
  38278. if (this._reflectionTexture) {
  38279. activeTextures.push(this._reflectionTexture);
  38280. }
  38281. if (this._emissiveTexture) {
  38282. activeTextures.push(this._emissiveTexture);
  38283. }
  38284. if (this._reflectivityTexture) {
  38285. activeTextures.push(this._reflectivityTexture);
  38286. }
  38287. if (this._metallicTexture) {
  38288. activeTextures.push(this._metallicTexture);
  38289. }
  38290. if (this._microSurfaceTexture) {
  38291. activeTextures.push(this._microSurfaceTexture);
  38292. }
  38293. if (this._bumpTexture) {
  38294. activeTextures.push(this._bumpTexture);
  38295. }
  38296. if (this._lightmapTexture) {
  38297. activeTextures.push(this._lightmapTexture);
  38298. }
  38299. if (this._refractionTexture) {
  38300. activeTextures.push(this._refractionTexture);
  38301. }
  38302. return activeTextures;
  38303. };
  38304. PBRMaterial.prototype.hasTexture = function (texture) {
  38305. if (_super.prototype.hasTexture.call(this, texture)) {
  38306. return true;
  38307. }
  38308. if (this._albedoTexture === texture) {
  38309. return true;
  38310. }
  38311. if (this._ambientTexture === texture) {
  38312. return true;
  38313. }
  38314. if (this._opacityTexture === texture) {
  38315. return true;
  38316. }
  38317. if (this._reflectionTexture === texture) {
  38318. return true;
  38319. }
  38320. if (this._reflectivityTexture === texture) {
  38321. return true;
  38322. }
  38323. if (this._metallicTexture === texture) {
  38324. return true;
  38325. }
  38326. if (this._microSurfaceTexture === texture) {
  38327. return true;
  38328. }
  38329. if (this._bumpTexture === texture) {
  38330. return true;
  38331. }
  38332. if (this._lightmapTexture === texture) {
  38333. return true;
  38334. }
  38335. if (this._refractionTexture === texture) {
  38336. return true;
  38337. }
  38338. return false;
  38339. };
  38340. PBRMaterial.prototype.clone = function (name) {
  38341. var _this = this;
  38342. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  38343. clone.id = name;
  38344. clone.name = name;
  38345. return clone;
  38346. };
  38347. PBRMaterial.prototype.serialize = function () {
  38348. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38349. serializationObject.customType = "BABYLON.PBRMaterial";
  38350. return serializationObject;
  38351. };
  38352. // Statics
  38353. PBRMaterial.Parse = function (source, scene, rootUrl) {
  38354. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  38355. };
  38356. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  38357. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  38358. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  38359. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  38360. __decorate([
  38361. BABYLON.serialize(),
  38362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38363. ], PBRMaterial.prototype, "directIntensity", void 0);
  38364. __decorate([
  38365. BABYLON.serialize(),
  38366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38367. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  38368. __decorate([
  38369. BABYLON.serialize(),
  38370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38371. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  38372. __decorate([
  38373. BABYLON.serialize(),
  38374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38375. ], PBRMaterial.prototype, "specularIntensity", void 0);
  38376. __decorate([
  38377. BABYLON.serialize(),
  38378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38379. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  38380. __decorate([
  38381. BABYLON.serializeAsTexture(),
  38382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38383. ], PBRMaterial.prototype, "albedoTexture", void 0);
  38384. __decorate([
  38385. BABYLON.serializeAsTexture(),
  38386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38387. ], PBRMaterial.prototype, "ambientTexture", void 0);
  38388. __decorate([
  38389. BABYLON.serialize(),
  38390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38391. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  38392. __decorate([
  38393. BABYLON.serializeAsTexture(),
  38394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38395. ], PBRMaterial.prototype, "opacityTexture", void 0);
  38396. __decorate([
  38397. BABYLON.serializeAsTexture(),
  38398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38399. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  38400. __decorate([
  38401. BABYLON.serializeAsTexture(),
  38402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38403. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  38404. __decorate([
  38405. BABYLON.serializeAsTexture(),
  38406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38407. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  38408. __decorate([
  38409. BABYLON.serializeAsTexture(),
  38410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38411. ], PBRMaterial.prototype, "metallicTexture", void 0);
  38412. __decorate([
  38413. BABYLON.serialize(),
  38414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38415. ], PBRMaterial.prototype, "metallic", void 0);
  38416. __decorate([
  38417. BABYLON.serialize(),
  38418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38419. ], PBRMaterial.prototype, "roughness", void 0);
  38420. __decorate([
  38421. BABYLON.serializeAsTexture(),
  38422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38423. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  38424. __decorate([
  38425. BABYLON.serializeAsTexture(),
  38426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38427. ], PBRMaterial.prototype, "bumpTexture", void 0);
  38428. __decorate([
  38429. BABYLON.serializeAsTexture(),
  38430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38431. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  38432. __decorate([
  38433. BABYLON.serializeAsTexture(),
  38434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38435. ], PBRMaterial.prototype, "refractionTexture", void 0);
  38436. __decorate([
  38437. BABYLON.serializeAsColor3("ambient"),
  38438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38439. ], PBRMaterial.prototype, "ambientColor", void 0);
  38440. __decorate([
  38441. BABYLON.serializeAsColor3("albedo"),
  38442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38443. ], PBRMaterial.prototype, "albedoColor", void 0);
  38444. __decorate([
  38445. BABYLON.serializeAsColor3("reflectivity"),
  38446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38447. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  38448. __decorate([
  38449. BABYLON.serializeAsColor3("reflection"),
  38450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38451. ], PBRMaterial.prototype, "reflectionColor", void 0);
  38452. __decorate([
  38453. BABYLON.serializeAsColor3("emissive"),
  38454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38455. ], PBRMaterial.prototype, "emissiveColor", void 0);
  38456. __decorate([
  38457. BABYLON.serialize(),
  38458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38459. ], PBRMaterial.prototype, "microSurface", void 0);
  38460. __decorate([
  38461. BABYLON.serialize(),
  38462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38463. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  38464. __decorate([
  38465. BABYLON.serialize(),
  38466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38467. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  38468. __decorate([
  38469. BABYLON.serialize(),
  38470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38471. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  38472. __decorate([
  38473. BABYLON.serialize(),
  38474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38475. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38476. __decorate([
  38477. BABYLON.serialize(),
  38478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38479. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  38480. __decorate([
  38481. BABYLON.serialize(),
  38482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38483. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  38484. __decorate([
  38485. BABYLON.serialize(),
  38486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38487. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  38488. __decorate([
  38489. BABYLON.serialize(),
  38490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38491. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  38492. __decorate([
  38493. BABYLON.serialize(),
  38494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38495. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  38496. __decorate([
  38497. BABYLON.serialize(),
  38498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38499. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  38500. __decorate([
  38501. BABYLON.serialize(),
  38502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38503. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  38504. __decorate([
  38505. BABYLON.serialize(),
  38506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38507. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  38508. __decorate([
  38509. BABYLON.serialize(),
  38510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38511. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  38512. __decorate([
  38513. BABYLON.serialize(),
  38514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38515. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  38516. __decorate([
  38517. BABYLON.serialize(),
  38518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38519. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  38520. __decorate([
  38521. BABYLON.serialize(),
  38522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38523. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  38524. __decorate([
  38525. BABYLON.serialize(),
  38526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38527. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  38528. __decorate([
  38529. BABYLON.serialize(),
  38530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38531. ], PBRMaterial.prototype, "useParallax", void 0);
  38532. __decorate([
  38533. BABYLON.serialize(),
  38534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38535. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  38536. __decorate([
  38537. BABYLON.serialize(),
  38538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38539. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  38540. __decorate([
  38541. BABYLON.serialize(),
  38542. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38543. ], PBRMaterial.prototype, "disableLighting", void 0);
  38544. __decorate([
  38545. BABYLON.serialize(),
  38546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38547. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  38548. __decorate([
  38549. BABYLON.serialize(),
  38550. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38551. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  38552. __decorate([
  38553. BABYLON.serialize(),
  38554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38555. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  38556. __decorate([
  38557. BABYLON.serialize(),
  38558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38559. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  38560. __decorate([
  38561. BABYLON.serialize(),
  38562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38563. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  38564. __decorate([
  38565. BABYLON.serialize(),
  38566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38567. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  38568. __decorate([
  38569. BABYLON.serialize(),
  38570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38571. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  38572. __decorate([
  38573. BABYLON.serializeAsTexture(),
  38574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38575. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  38576. __decorate([
  38577. BABYLON.serialize(),
  38578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38579. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  38580. __decorate([
  38581. BABYLON.serialize(),
  38582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38583. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  38584. __decorate([
  38585. BABYLON.serialize(),
  38586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38587. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  38588. return PBRMaterial;
  38589. }(BABYLON.PBRBaseMaterial));
  38590. BABYLON.PBRMaterial = PBRMaterial;
  38591. })(BABYLON || (BABYLON = {}));
  38592. //# sourceMappingURL=babylon.pbrMaterial.js.map
  38593. var BABYLON;
  38594. (function (BABYLON) {
  38595. /**
  38596. * The PBR material of BJS following the metal roughness convention.
  38597. *
  38598. * This fits to the PBR convention in the GLTF definition:
  38599. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  38600. */
  38601. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  38602. __extends(PBRMetallicRoughnessMaterial, _super);
  38603. /**
  38604. * Instantiates a new PBRMetalRoughnessMaterial instance.
  38605. *
  38606. * @param name The material name
  38607. * @param scene The scene the material will be use in.
  38608. */
  38609. function PBRMetallicRoughnessMaterial(name, scene) {
  38610. var _this = _super.call(this, name, scene) || this;
  38611. _this._useRoughnessFromMetallicTextureAlpha = false;
  38612. _this._useRoughnessFromMetallicTextureGreen = true;
  38613. _this._useMetallnessFromMetallicTextureBlue = true;
  38614. _this._forceMetallicWorkflow = true;
  38615. return _this;
  38616. }
  38617. /**
  38618. * Return the currrent class name of the material.
  38619. */
  38620. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  38621. return "PBRMetallicRoughnessMaterial";
  38622. };
  38623. /**
  38624. * Return the active textures of the material.
  38625. */
  38626. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  38627. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38628. if (this.baseTexture) {
  38629. activeTextures.push(this.baseTexture);
  38630. }
  38631. if (this.metallicRoughnessTexture) {
  38632. activeTextures.push(this.metallicRoughnessTexture);
  38633. }
  38634. return activeTextures;
  38635. };
  38636. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  38637. if (_super.prototype.hasTexture.call(this, texture)) {
  38638. return true;
  38639. }
  38640. if (this.baseTexture === texture) {
  38641. return true;
  38642. }
  38643. if (this.metallicRoughnessTexture === texture) {
  38644. return true;
  38645. }
  38646. return false;
  38647. };
  38648. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  38649. var _this = this;
  38650. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  38651. clone.id = name;
  38652. clone.name = name;
  38653. return clone;
  38654. };
  38655. /**
  38656. * Serialize the material to a parsable JSON object.
  38657. */
  38658. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  38659. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38660. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  38661. return serializationObject;
  38662. };
  38663. /**
  38664. * Parses a JSON object correponding to the serialize function.
  38665. */
  38666. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  38667. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  38668. };
  38669. __decorate([
  38670. BABYLON.serializeAsColor3(),
  38671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38672. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  38673. __decorate([
  38674. BABYLON.serializeAsTexture(),
  38675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38676. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  38677. __decorate([
  38678. BABYLON.serialize(),
  38679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38680. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  38681. __decorate([
  38682. BABYLON.serialize(),
  38683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38684. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  38685. __decorate([
  38686. BABYLON.serializeAsTexture(),
  38687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  38688. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  38689. return PBRMetallicRoughnessMaterial;
  38690. }(BABYLON.PBRBaseSimpleMaterial));
  38691. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  38692. })(BABYLON || (BABYLON = {}));
  38693. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  38694. var BABYLON;
  38695. (function (BABYLON) {
  38696. /**
  38697. * The PBR material of BJS following the specular glossiness convention.
  38698. *
  38699. * This fits to the PBR convention in the GLTF definition:
  38700. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  38701. */
  38702. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  38703. __extends(PBRSpecularGlossinessMaterial, _super);
  38704. /**
  38705. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  38706. *
  38707. * @param name The material name
  38708. * @param scene The scene the material will be use in.
  38709. */
  38710. function PBRSpecularGlossinessMaterial(name, scene) {
  38711. var _this = _super.call(this, name, scene) || this;
  38712. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  38713. return _this;
  38714. }
  38715. /**
  38716. * Return the currrent class name of the material.
  38717. */
  38718. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  38719. return "PBRSpecularGlossinessMaterial";
  38720. };
  38721. /**
  38722. * Return the active textures of the material.
  38723. */
  38724. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  38725. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38726. if (this.diffuseTexture) {
  38727. activeTextures.push(this.diffuseTexture);
  38728. }
  38729. if (this.specularGlossinessTexture) {
  38730. activeTextures.push(this.specularGlossinessTexture);
  38731. }
  38732. return activeTextures;
  38733. };
  38734. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  38735. if (_super.prototype.hasTexture.call(this, texture)) {
  38736. return true;
  38737. }
  38738. if (this.diffuseTexture === texture) {
  38739. return true;
  38740. }
  38741. if (this.specularGlossinessTexture === texture) {
  38742. return true;
  38743. }
  38744. return false;
  38745. };
  38746. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  38747. var _this = this;
  38748. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  38749. clone.id = name;
  38750. clone.name = name;
  38751. return clone;
  38752. };
  38753. /**
  38754. * Serialize the material to a parsable JSON object.
  38755. */
  38756. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  38757. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38758. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  38759. return serializationObject;
  38760. };
  38761. /**
  38762. * Parses a JSON object correponding to the serialize function.
  38763. */
  38764. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  38765. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  38766. };
  38767. __decorate([
  38768. BABYLON.serializeAsColor3("diffuse"),
  38769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38770. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  38771. __decorate([
  38772. BABYLON.serializeAsTexture(),
  38773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38774. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  38775. __decorate([
  38776. BABYLON.serializeAsColor3("specular"),
  38777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  38778. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  38779. __decorate([
  38780. BABYLON.serialize(),
  38781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  38782. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  38783. __decorate([
  38784. BABYLON.serializeAsTexture(),
  38785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  38786. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  38787. return PBRSpecularGlossinessMaterial;
  38788. }(BABYLON.PBRBaseSimpleMaterial));
  38789. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  38790. })(BABYLON || (BABYLON = {}));
  38791. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  38792. var BABYLON;
  38793. (function (BABYLON) {
  38794. BABYLON.CameraInputTypes = {};
  38795. var CameraInputsManager = /** @class */ (function () {
  38796. function CameraInputsManager(camera) {
  38797. this.attached = {};
  38798. this.camera = camera;
  38799. this.checkInputs = function () { };
  38800. }
  38801. CameraInputsManager.prototype.add = function (input) {
  38802. var type = input.getSimpleName();
  38803. if (this.attached[type]) {
  38804. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  38805. return;
  38806. }
  38807. this.attached[type] = input;
  38808. input.camera = this.camera;
  38809. //for checkInputs, we are dynamically creating a function
  38810. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  38811. if (input.checkInputs) {
  38812. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38813. }
  38814. if (this.attachedElement) {
  38815. input.attachControl(this.attachedElement);
  38816. }
  38817. };
  38818. CameraInputsManager.prototype.remove = function (inputToRemove) {
  38819. for (var cam in this.attached) {
  38820. var input = this.attached[cam];
  38821. if (input === inputToRemove) {
  38822. input.detachControl(this.attachedElement);
  38823. input.camera = null;
  38824. delete this.attached[cam];
  38825. this.rebuildInputCheck();
  38826. }
  38827. }
  38828. };
  38829. CameraInputsManager.prototype.removeByType = function (inputType) {
  38830. for (var cam in this.attached) {
  38831. var input = this.attached[cam];
  38832. if (input.getClassName() === inputType) {
  38833. input.detachControl(this.attachedElement);
  38834. input.camera = null;
  38835. delete this.attached[cam];
  38836. this.rebuildInputCheck();
  38837. }
  38838. }
  38839. };
  38840. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  38841. var current = this.checkInputs;
  38842. return function () {
  38843. current();
  38844. fn();
  38845. };
  38846. };
  38847. CameraInputsManager.prototype.attachInput = function (input) {
  38848. if (this.attachedElement) {
  38849. input.attachControl(this.attachedElement, this.noPreventDefault);
  38850. }
  38851. };
  38852. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  38853. if (noPreventDefault === void 0) { noPreventDefault = false; }
  38854. if (this.attachedElement) {
  38855. return;
  38856. }
  38857. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  38858. this.attachedElement = element;
  38859. this.noPreventDefault = noPreventDefault;
  38860. for (var cam in this.attached) {
  38861. this.attached[cam].attachControl(element, noPreventDefault);
  38862. }
  38863. };
  38864. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  38865. if (disconnect === void 0) { disconnect = false; }
  38866. if (this.attachedElement !== element) {
  38867. return;
  38868. }
  38869. for (var cam in this.attached) {
  38870. this.attached[cam].detachControl(element);
  38871. if (disconnect) {
  38872. this.attached[cam].camera = null;
  38873. }
  38874. }
  38875. this.attachedElement = null;
  38876. };
  38877. CameraInputsManager.prototype.rebuildInputCheck = function () {
  38878. this.checkInputs = function () { };
  38879. for (var cam in this.attached) {
  38880. var input = this.attached[cam];
  38881. if (input.checkInputs) {
  38882. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38883. }
  38884. }
  38885. };
  38886. CameraInputsManager.prototype.clear = function () {
  38887. if (this.attachedElement) {
  38888. this.detachElement(this.attachedElement, true);
  38889. }
  38890. this.attached = {};
  38891. this.attachedElement = null;
  38892. this.checkInputs = function () { };
  38893. };
  38894. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  38895. var inputs = {};
  38896. for (var cam in this.attached) {
  38897. var input = this.attached[cam];
  38898. var res = BABYLON.SerializationHelper.Serialize(input);
  38899. inputs[input.getClassName()] = res;
  38900. }
  38901. serializedCamera.inputsmgr = inputs;
  38902. };
  38903. CameraInputsManager.prototype.parse = function (parsedCamera) {
  38904. var parsedInputs = parsedCamera.inputsmgr;
  38905. if (parsedInputs) {
  38906. this.clear();
  38907. for (var n in parsedInputs) {
  38908. var construct = BABYLON.CameraInputTypes[n];
  38909. if (construct) {
  38910. var parsedinput = parsedInputs[n];
  38911. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  38912. this.add(input);
  38913. }
  38914. }
  38915. }
  38916. else {
  38917. //2016-03-08 this part is for managing backward compatibility
  38918. for (var n in this.attached) {
  38919. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  38920. if (construct) {
  38921. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  38922. this.remove(this.attached[n]);
  38923. this.add(input);
  38924. }
  38925. }
  38926. }
  38927. };
  38928. return CameraInputsManager;
  38929. }());
  38930. BABYLON.CameraInputsManager = CameraInputsManager;
  38931. })(BABYLON || (BABYLON = {}));
  38932. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  38933. var BABYLON;
  38934. (function (BABYLON) {
  38935. var TargetCamera = /** @class */ (function (_super) {
  38936. __extends(TargetCamera, _super);
  38937. function TargetCamera(name, position, scene) {
  38938. var _this = _super.call(this, name, position, scene) || this;
  38939. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38940. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  38941. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  38942. _this.speed = 2.0;
  38943. _this.noRotationConstraint = false;
  38944. _this.lockedTarget = null;
  38945. _this._currentTarget = BABYLON.Vector3.Zero();
  38946. _this._viewMatrix = BABYLON.Matrix.Zero();
  38947. _this._camMatrix = BABYLON.Matrix.Zero();
  38948. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  38949. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  38950. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  38951. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  38952. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  38953. _this._lookAtTemp = BABYLON.Matrix.Zero();
  38954. _this._tempMatrix = BABYLON.Matrix.Zero();
  38955. return _this;
  38956. }
  38957. TargetCamera.prototype.getFrontPosition = function (distance) {
  38958. this.getWorldMatrix();
  38959. var direction = this.getTarget().subtract(this.position);
  38960. direction.normalize();
  38961. direction.scaleInPlace(distance);
  38962. return this.globalPosition.add(direction);
  38963. };
  38964. TargetCamera.prototype._getLockedTargetPosition = function () {
  38965. if (!this.lockedTarget) {
  38966. return null;
  38967. }
  38968. if (this.lockedTarget.absolutePosition) {
  38969. this.lockedTarget.computeWorldMatrix();
  38970. }
  38971. return this.lockedTarget.absolutePosition || this.lockedTarget;
  38972. };
  38973. TargetCamera.prototype.storeState = function () {
  38974. this._storedPosition = this.position.clone();
  38975. this._storedRotation = this.rotation.clone();
  38976. if (this.rotationQuaternion) {
  38977. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  38978. }
  38979. return _super.prototype.storeState.call(this);
  38980. };
  38981. /**
  38982. * Restored camera state. You must call storeState() first
  38983. */
  38984. TargetCamera.prototype._restoreStateValues = function () {
  38985. if (!_super.prototype._restoreStateValues.call(this)) {
  38986. return false;
  38987. }
  38988. this.position = this._storedPosition.clone();
  38989. this.rotation = this._storedRotation.clone();
  38990. if (this.rotationQuaternion) {
  38991. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  38992. }
  38993. this.cameraDirection.copyFromFloats(0, 0, 0);
  38994. this.cameraRotation.copyFromFloats(0, 0);
  38995. return true;
  38996. };
  38997. // Cache
  38998. TargetCamera.prototype._initCache = function () {
  38999. _super.prototype._initCache.call(this);
  39000. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39001. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39002. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39003. };
  39004. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  39005. if (!ignoreParentClass) {
  39006. _super.prototype._updateCache.call(this);
  39007. }
  39008. var lockedTargetPosition = this._getLockedTargetPosition();
  39009. if (!lockedTargetPosition) {
  39010. this._cache.lockedTarget = null;
  39011. }
  39012. else {
  39013. if (!this._cache.lockedTarget) {
  39014. this._cache.lockedTarget = lockedTargetPosition.clone();
  39015. }
  39016. else {
  39017. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  39018. }
  39019. }
  39020. this._cache.rotation.copyFrom(this.rotation);
  39021. if (this.rotationQuaternion)
  39022. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39023. };
  39024. // Synchronized
  39025. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  39026. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  39027. return false;
  39028. }
  39029. var lockedTargetPosition = this._getLockedTargetPosition();
  39030. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  39031. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  39032. };
  39033. // Methods
  39034. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  39035. var engine = this.getEngine();
  39036. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  39037. };
  39038. // Target
  39039. TargetCamera.prototype.setTarget = function (target) {
  39040. this.upVector.normalize();
  39041. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  39042. this._camMatrix.invert();
  39043. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  39044. var vDir = target.subtract(this.position);
  39045. if (vDir.x >= 0.0) {
  39046. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  39047. }
  39048. else {
  39049. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  39050. }
  39051. this.rotation.z = 0;
  39052. if (isNaN(this.rotation.x)) {
  39053. this.rotation.x = 0;
  39054. }
  39055. if (isNaN(this.rotation.y)) {
  39056. this.rotation.y = 0;
  39057. }
  39058. if (isNaN(this.rotation.z)) {
  39059. this.rotation.z = 0;
  39060. }
  39061. if (this.rotationQuaternion) {
  39062. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39063. }
  39064. };
  39065. /**
  39066. * Return the current target position of the camera. This value is expressed in local space.
  39067. */
  39068. TargetCamera.prototype.getTarget = function () {
  39069. return this._currentTarget;
  39070. };
  39071. TargetCamera.prototype._decideIfNeedsToMove = function () {
  39072. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39073. };
  39074. TargetCamera.prototype._updatePosition = function () {
  39075. if (this.parent) {
  39076. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  39077. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  39078. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  39079. return;
  39080. }
  39081. this.position.addInPlace(this.cameraDirection);
  39082. };
  39083. TargetCamera.prototype._checkInputs = function () {
  39084. var needToMove = this._decideIfNeedsToMove();
  39085. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  39086. // Move
  39087. if (needToMove) {
  39088. this._updatePosition();
  39089. }
  39090. // Rotate
  39091. if (needToRotate) {
  39092. this.rotation.x += this.cameraRotation.x;
  39093. this.rotation.y += this.cameraRotation.y;
  39094. //rotate, if quaternion is set and rotation was used
  39095. if (this.rotationQuaternion) {
  39096. var len = this.rotation.lengthSquared();
  39097. if (len) {
  39098. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39099. }
  39100. }
  39101. if (!this.noRotationConstraint) {
  39102. var limit = (Math.PI / 2) * 0.95;
  39103. if (this.rotation.x > limit)
  39104. this.rotation.x = limit;
  39105. if (this.rotation.x < -limit)
  39106. this.rotation.x = -limit;
  39107. }
  39108. }
  39109. // Inertia
  39110. if (needToMove) {
  39111. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  39112. this.cameraDirection.x = 0;
  39113. }
  39114. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  39115. this.cameraDirection.y = 0;
  39116. }
  39117. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  39118. this.cameraDirection.z = 0;
  39119. }
  39120. this.cameraDirection.scaleInPlace(this.inertia);
  39121. }
  39122. if (needToRotate) {
  39123. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  39124. this.cameraRotation.x = 0;
  39125. }
  39126. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  39127. this.cameraRotation.y = 0;
  39128. }
  39129. this.cameraRotation.scaleInPlace(this.inertia);
  39130. }
  39131. _super.prototype._checkInputs.call(this);
  39132. };
  39133. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  39134. if (this.rotationQuaternion) {
  39135. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  39136. }
  39137. else {
  39138. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  39139. }
  39140. //update the up vector!
  39141. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  39142. };
  39143. TargetCamera.prototype._getViewMatrix = function () {
  39144. if (this.lockedTarget) {
  39145. this.setTarget(this._getLockedTargetPosition());
  39146. }
  39147. // Compute
  39148. this._updateCameraRotationMatrix();
  39149. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  39150. // Computing target and final matrix
  39151. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  39152. if (this.getScene().useRightHandedSystem) {
  39153. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39154. }
  39155. else {
  39156. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39157. }
  39158. return this._viewMatrix;
  39159. };
  39160. /**
  39161. * @override
  39162. * Override Camera.createRigCamera
  39163. */
  39164. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39165. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  39166. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  39167. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  39168. if (!this.rotationQuaternion) {
  39169. this.rotationQuaternion = new BABYLON.Quaternion();
  39170. }
  39171. rigCamera._cameraRigParams = {};
  39172. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  39173. }
  39174. return rigCamera;
  39175. }
  39176. return null;
  39177. };
  39178. /**
  39179. * @override
  39180. * Override Camera._updateRigCameras
  39181. */
  39182. TargetCamera.prototype._updateRigCameras = function () {
  39183. var camLeft = this._rigCameras[0];
  39184. var camRight = this._rigCameras[1];
  39185. switch (this.cameraRigMode) {
  39186. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39187. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39188. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39189. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39190. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  39191. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  39192. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  39193. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  39194. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  39195. camLeft.setTarget(this.getTarget());
  39196. camRight.setTarget(this.getTarget());
  39197. break;
  39198. case BABYLON.Camera.RIG_MODE_VR:
  39199. if (camLeft.rotationQuaternion) {
  39200. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39201. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39202. }
  39203. else {
  39204. camLeft.rotation.copyFrom(this.rotation);
  39205. camRight.rotation.copyFrom(this.rotation);
  39206. }
  39207. camLeft.position.copyFrom(this.position);
  39208. camRight.position.copyFrom(this.position);
  39209. break;
  39210. }
  39211. _super.prototype._updateRigCameras.call(this);
  39212. };
  39213. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  39214. if (!this._rigCamTransformMatrix) {
  39215. this._rigCamTransformMatrix = new BABYLON.Matrix();
  39216. }
  39217. var target = this.getTarget();
  39218. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  39219. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  39220. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  39221. };
  39222. TargetCamera.prototype.getClassName = function () {
  39223. return "TargetCamera";
  39224. };
  39225. __decorate([
  39226. BABYLON.serializeAsVector3()
  39227. ], TargetCamera.prototype, "rotation", void 0);
  39228. __decorate([
  39229. BABYLON.serialize()
  39230. ], TargetCamera.prototype, "speed", void 0);
  39231. __decorate([
  39232. BABYLON.serializeAsMeshReference("lockedTargetId")
  39233. ], TargetCamera.prototype, "lockedTarget", void 0);
  39234. return TargetCamera;
  39235. }(BABYLON.Camera));
  39236. BABYLON.TargetCamera = TargetCamera;
  39237. })(BABYLON || (BABYLON = {}));
  39238. //# sourceMappingURL=babylon.targetCamera.js.map
  39239. var BABYLON;
  39240. (function (BABYLON) {
  39241. var FreeCameraMouseInput = /** @class */ (function () {
  39242. function FreeCameraMouseInput(touchEnabled) {
  39243. if (touchEnabled === void 0) { touchEnabled = true; }
  39244. this.touchEnabled = touchEnabled;
  39245. this.buttons = [0, 1, 2];
  39246. this.angularSensibility = 2000.0;
  39247. this.previousPosition = null;
  39248. }
  39249. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  39250. var _this = this;
  39251. var engine = this.camera.getEngine();
  39252. if (!this._pointerInput) {
  39253. this._pointerInput = function (p, s) {
  39254. var evt = p.event;
  39255. if (engine.isInVRExclusivePointerMode) {
  39256. return;
  39257. }
  39258. if (!_this.touchEnabled && evt.pointerType === "touch") {
  39259. return;
  39260. }
  39261. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39262. return;
  39263. }
  39264. var srcElement = (evt.srcElement || evt.target);
  39265. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  39266. try {
  39267. srcElement.setPointerCapture(evt.pointerId);
  39268. }
  39269. catch (e) {
  39270. //Nothing to do with the error. Execution will continue.
  39271. }
  39272. _this.previousPosition = {
  39273. x: evt.clientX,
  39274. y: evt.clientY
  39275. };
  39276. if (!noPreventDefault) {
  39277. evt.preventDefault();
  39278. element.focus();
  39279. }
  39280. }
  39281. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  39282. try {
  39283. srcElement.releasePointerCapture(evt.pointerId);
  39284. }
  39285. catch (e) {
  39286. //Nothing to do with the error.
  39287. }
  39288. _this.previousPosition = null;
  39289. if (!noPreventDefault) {
  39290. evt.preventDefault();
  39291. }
  39292. }
  39293. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39294. if (!_this.previousPosition || engine.isPointerLock) {
  39295. return;
  39296. }
  39297. var offsetX = evt.clientX - _this.previousPosition.x;
  39298. var offsetY = evt.clientY - _this.previousPosition.y;
  39299. if (_this.camera.getScene().useRightHandedSystem) {
  39300. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  39301. }
  39302. else {
  39303. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  39304. }
  39305. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  39306. _this.previousPosition = {
  39307. x: evt.clientX,
  39308. y: evt.clientY
  39309. };
  39310. if (!noPreventDefault) {
  39311. evt.preventDefault();
  39312. }
  39313. }
  39314. };
  39315. }
  39316. this._onMouseMove = function (evt) {
  39317. if (!engine.isPointerLock) {
  39318. return;
  39319. }
  39320. if (engine.isInVRExclusivePointerMode) {
  39321. return;
  39322. }
  39323. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  39324. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  39325. if (_this.camera.getScene().useRightHandedSystem) {
  39326. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  39327. }
  39328. else {
  39329. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  39330. }
  39331. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  39332. _this.previousPosition = null;
  39333. if (!noPreventDefault) {
  39334. evt.preventDefault();
  39335. }
  39336. };
  39337. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  39338. element.addEventListener("mousemove", this._onMouseMove, false);
  39339. };
  39340. FreeCameraMouseInput.prototype.detachControl = function (element) {
  39341. if (this._observer && element) {
  39342. this.camera.getScene().onPointerObservable.remove(this._observer);
  39343. if (this._onMouseMove) {
  39344. element.removeEventListener("mousemove", this._onMouseMove);
  39345. }
  39346. this._observer = null;
  39347. this._onMouseMove = null;
  39348. this.previousPosition = null;
  39349. }
  39350. };
  39351. FreeCameraMouseInput.prototype.getClassName = function () {
  39352. return "FreeCameraMouseInput";
  39353. };
  39354. FreeCameraMouseInput.prototype.getSimpleName = function () {
  39355. return "mouse";
  39356. };
  39357. __decorate([
  39358. BABYLON.serialize()
  39359. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  39360. __decorate([
  39361. BABYLON.serialize()
  39362. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  39363. return FreeCameraMouseInput;
  39364. }());
  39365. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  39366. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  39367. })(BABYLON || (BABYLON = {}));
  39368. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  39369. var BABYLON;
  39370. (function (BABYLON) {
  39371. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  39372. function FreeCameraKeyboardMoveInput() {
  39373. this._keys = new Array();
  39374. this.keysUp = [38];
  39375. this.keysDown = [40];
  39376. this.keysLeft = [37];
  39377. this.keysRight = [39];
  39378. }
  39379. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39380. var _this = this;
  39381. if (this._onCanvasBlurObserver) {
  39382. return;
  39383. }
  39384. this._scene = this.camera.getScene();
  39385. this._engine = this._scene.getEngine();
  39386. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39387. _this._keys = [];
  39388. });
  39389. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39390. var evt = info.event;
  39391. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39392. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39393. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39394. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39395. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  39396. var index = _this._keys.indexOf(evt.keyCode);
  39397. if (index === -1) {
  39398. _this._keys.push(evt.keyCode);
  39399. }
  39400. if (!noPreventDefault) {
  39401. evt.preventDefault();
  39402. }
  39403. }
  39404. }
  39405. else {
  39406. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39407. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39408. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39409. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  39410. var index = _this._keys.indexOf(evt.keyCode);
  39411. if (index >= 0) {
  39412. _this._keys.splice(index, 1);
  39413. }
  39414. if (!noPreventDefault) {
  39415. evt.preventDefault();
  39416. }
  39417. }
  39418. }
  39419. });
  39420. };
  39421. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39422. if (this._scene) {
  39423. if (this._onKeyboardObserver) {
  39424. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39425. }
  39426. if (this._onCanvasBlurObserver) {
  39427. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39428. }
  39429. this._onKeyboardObserver = null;
  39430. this._onCanvasBlurObserver = null;
  39431. }
  39432. this._keys = [];
  39433. };
  39434. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39435. if (this._onKeyboardObserver) {
  39436. var camera = this.camera;
  39437. // Keyboard
  39438. for (var index = 0; index < this._keys.length; index++) {
  39439. var keyCode = this._keys[index];
  39440. var speed = camera._computeLocalCameraSpeed();
  39441. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39442. camera._localDirection.copyFromFloats(-speed, 0, 0);
  39443. }
  39444. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39445. camera._localDirection.copyFromFloats(0, 0, speed);
  39446. }
  39447. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39448. camera._localDirection.copyFromFloats(speed, 0, 0);
  39449. }
  39450. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39451. camera._localDirection.copyFromFloats(0, 0, -speed);
  39452. }
  39453. if (camera.getScene().useRightHandedSystem) {
  39454. camera._localDirection.z *= -1;
  39455. }
  39456. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  39457. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  39458. camera.cameraDirection.addInPlace(camera._transformedDirection);
  39459. }
  39460. }
  39461. };
  39462. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  39463. return "FreeCameraKeyboardMoveInput";
  39464. };
  39465. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  39466. this._keys = [];
  39467. };
  39468. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39469. return "keyboard";
  39470. };
  39471. __decorate([
  39472. BABYLON.serialize()
  39473. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39474. __decorate([
  39475. BABYLON.serialize()
  39476. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39477. __decorate([
  39478. BABYLON.serialize()
  39479. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39480. __decorate([
  39481. BABYLON.serialize()
  39482. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39483. return FreeCameraKeyboardMoveInput;
  39484. }());
  39485. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  39486. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  39487. })(BABYLON || (BABYLON = {}));
  39488. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  39489. var BABYLON;
  39490. (function (BABYLON) {
  39491. var FreeCameraInputsManager = /** @class */ (function (_super) {
  39492. __extends(FreeCameraInputsManager, _super);
  39493. function FreeCameraInputsManager(camera) {
  39494. return _super.call(this, camera) || this;
  39495. }
  39496. FreeCameraInputsManager.prototype.addKeyboard = function () {
  39497. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  39498. return this;
  39499. };
  39500. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  39501. if (touchEnabled === void 0) { touchEnabled = true; }
  39502. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  39503. return this;
  39504. };
  39505. FreeCameraInputsManager.prototype.addGamepad = function () {
  39506. this.add(new BABYLON.FreeCameraGamepadInput());
  39507. return this;
  39508. };
  39509. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  39510. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  39511. return this;
  39512. };
  39513. FreeCameraInputsManager.prototype.addTouch = function () {
  39514. this.add(new BABYLON.FreeCameraTouchInput());
  39515. return this;
  39516. };
  39517. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  39518. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  39519. return this;
  39520. };
  39521. return FreeCameraInputsManager;
  39522. }(BABYLON.CameraInputsManager));
  39523. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  39524. })(BABYLON || (BABYLON = {}));
  39525. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  39526. var BABYLON;
  39527. (function (BABYLON) {
  39528. var FreeCamera = /** @class */ (function (_super) {
  39529. __extends(FreeCamera, _super);
  39530. function FreeCamera(name, position, scene) {
  39531. var _this = _super.call(this, name, position, scene) || this;
  39532. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  39533. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  39534. _this.checkCollisions = false;
  39535. _this.applyGravity = false;
  39536. _this._needMoveForGravity = false;
  39537. _this._oldPosition = BABYLON.Vector3.Zero();
  39538. _this._diffPosition = BABYLON.Vector3.Zero();
  39539. _this._newPosition = BABYLON.Vector3.Zero();
  39540. // Collisions
  39541. _this._collisionMask = -1;
  39542. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39543. if (collidedMesh === void 0) { collidedMesh = null; }
  39544. //TODO move this to the collision coordinator!
  39545. if (_this.getScene().workerCollisions)
  39546. newPosition.multiplyInPlace(_this._collider._radius);
  39547. var updatePosition = function (newPos) {
  39548. _this._newPosition.copyFrom(newPos);
  39549. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  39550. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  39551. _this.position.addInPlace(_this._diffPosition);
  39552. if (_this.onCollide && collidedMesh) {
  39553. _this.onCollide(collidedMesh);
  39554. }
  39555. }
  39556. };
  39557. updatePosition(newPosition);
  39558. };
  39559. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  39560. _this.inputs.addKeyboard().addMouse();
  39561. return _this;
  39562. }
  39563. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  39564. //-- begin properties for backward compatibility for inputs
  39565. get: function () {
  39566. var mouse = this.inputs.attached["mouse"];
  39567. if (mouse)
  39568. return mouse.angularSensibility;
  39569. return 0;
  39570. },
  39571. set: function (value) {
  39572. var mouse = this.inputs.attached["mouse"];
  39573. if (mouse)
  39574. mouse.angularSensibility = value;
  39575. },
  39576. enumerable: true,
  39577. configurable: true
  39578. });
  39579. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  39580. get: function () {
  39581. var keyboard = this.inputs.attached["keyboard"];
  39582. if (keyboard)
  39583. return keyboard.keysUp;
  39584. return [];
  39585. },
  39586. set: function (value) {
  39587. var keyboard = this.inputs.attached["keyboard"];
  39588. if (keyboard)
  39589. keyboard.keysUp = value;
  39590. },
  39591. enumerable: true,
  39592. configurable: true
  39593. });
  39594. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  39595. get: function () {
  39596. var keyboard = this.inputs.attached["keyboard"];
  39597. if (keyboard)
  39598. return keyboard.keysDown;
  39599. return [];
  39600. },
  39601. set: function (value) {
  39602. var keyboard = this.inputs.attached["keyboard"];
  39603. if (keyboard)
  39604. keyboard.keysDown = value;
  39605. },
  39606. enumerable: true,
  39607. configurable: true
  39608. });
  39609. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  39610. get: function () {
  39611. var keyboard = this.inputs.attached["keyboard"];
  39612. if (keyboard)
  39613. return keyboard.keysLeft;
  39614. return [];
  39615. },
  39616. set: function (value) {
  39617. var keyboard = this.inputs.attached["keyboard"];
  39618. if (keyboard)
  39619. keyboard.keysLeft = value;
  39620. },
  39621. enumerable: true,
  39622. configurable: true
  39623. });
  39624. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  39625. get: function () {
  39626. var keyboard = this.inputs.attached["keyboard"];
  39627. if (keyboard)
  39628. return keyboard.keysRight;
  39629. return [];
  39630. },
  39631. set: function (value) {
  39632. var keyboard = this.inputs.attached["keyboard"];
  39633. if (keyboard)
  39634. keyboard.keysRight = value;
  39635. },
  39636. enumerable: true,
  39637. configurable: true
  39638. });
  39639. // Controls
  39640. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  39641. this.inputs.attachElement(element, noPreventDefault);
  39642. };
  39643. FreeCamera.prototype.detachControl = function (element) {
  39644. this.inputs.detachElement(element);
  39645. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  39646. this.cameraRotation = new BABYLON.Vector2(0, 0);
  39647. };
  39648. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  39649. get: function () {
  39650. return this._collisionMask;
  39651. },
  39652. set: function (mask) {
  39653. this._collisionMask = !isNaN(mask) ? mask : -1;
  39654. },
  39655. enumerable: true,
  39656. configurable: true
  39657. });
  39658. FreeCamera.prototype._collideWithWorld = function (displacement) {
  39659. var globalPosition;
  39660. if (this.parent) {
  39661. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  39662. }
  39663. else {
  39664. globalPosition = this.position;
  39665. }
  39666. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  39667. this._oldPosition.addInPlace(this.ellipsoidOffset);
  39668. if (!this._collider) {
  39669. this._collider = new BABYLON.Collider();
  39670. }
  39671. this._collider._radius = this.ellipsoid;
  39672. this._collider.collisionMask = this._collisionMask;
  39673. //no need for clone, as long as gravity is not on.
  39674. var actualDisplacement = displacement;
  39675. //add gravity to the direction to prevent the dual-collision checking
  39676. if (this.applyGravity) {
  39677. //this prevents mending with cameraDirection, a global variable of the free camera class.
  39678. actualDisplacement = displacement.add(this.getScene().gravity);
  39679. }
  39680. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39681. };
  39682. FreeCamera.prototype._checkInputs = function () {
  39683. if (!this._localDirection) {
  39684. this._localDirection = BABYLON.Vector3.Zero();
  39685. this._transformedDirection = BABYLON.Vector3.Zero();
  39686. }
  39687. this.inputs.checkInputs();
  39688. _super.prototype._checkInputs.call(this);
  39689. };
  39690. FreeCamera.prototype._decideIfNeedsToMove = function () {
  39691. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39692. };
  39693. FreeCamera.prototype._updatePosition = function () {
  39694. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  39695. this._collideWithWorld(this.cameraDirection);
  39696. }
  39697. else {
  39698. _super.prototype._updatePosition.call(this);
  39699. }
  39700. };
  39701. FreeCamera.prototype.dispose = function () {
  39702. this.inputs.clear();
  39703. _super.prototype.dispose.call(this);
  39704. };
  39705. FreeCamera.prototype.getClassName = function () {
  39706. return "FreeCamera";
  39707. };
  39708. __decorate([
  39709. BABYLON.serializeAsVector3()
  39710. ], FreeCamera.prototype, "ellipsoid", void 0);
  39711. __decorate([
  39712. BABYLON.serializeAsVector3()
  39713. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  39714. __decorate([
  39715. BABYLON.serialize()
  39716. ], FreeCamera.prototype, "checkCollisions", void 0);
  39717. __decorate([
  39718. BABYLON.serialize()
  39719. ], FreeCamera.prototype, "applyGravity", void 0);
  39720. return FreeCamera;
  39721. }(BABYLON.TargetCamera));
  39722. BABYLON.FreeCamera = FreeCamera;
  39723. })(BABYLON || (BABYLON = {}));
  39724. //# sourceMappingURL=babylon.freeCamera.js.map
  39725. var BABYLON;
  39726. (function (BABYLON) {
  39727. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  39728. function ArcRotateCameraKeyboardMoveInput() {
  39729. this._keys = new Array();
  39730. this.keysUp = [38];
  39731. this.keysDown = [40];
  39732. this.keysLeft = [37];
  39733. this.keysRight = [39];
  39734. this.keysReset = [220];
  39735. this.panningSensibility = 50.0;
  39736. this.zoomingSensibility = 25.0;
  39737. this.useAltToZoom = true;
  39738. }
  39739. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39740. var _this = this;
  39741. if (this._onCanvasBlurObserver) {
  39742. return;
  39743. }
  39744. this._scene = this.camera.getScene();
  39745. this._engine = this._scene.getEngine();
  39746. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39747. _this._keys = [];
  39748. });
  39749. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39750. var evt = info.event;
  39751. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39752. _this._ctrlPressed = evt.ctrlKey;
  39753. _this._altPressed = evt.altKey;
  39754. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39755. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39756. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39757. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39758. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39759. var index = _this._keys.indexOf(evt.keyCode);
  39760. if (index === -1) {
  39761. _this._keys.push(evt.keyCode);
  39762. }
  39763. if (evt.preventDefault) {
  39764. if (!noPreventDefault) {
  39765. evt.preventDefault();
  39766. }
  39767. }
  39768. }
  39769. }
  39770. else {
  39771. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39772. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39773. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39774. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39775. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39776. var index = _this._keys.indexOf(evt.keyCode);
  39777. if (index >= 0) {
  39778. _this._keys.splice(index, 1);
  39779. }
  39780. if (evt.preventDefault) {
  39781. if (!noPreventDefault) {
  39782. evt.preventDefault();
  39783. }
  39784. }
  39785. }
  39786. }
  39787. });
  39788. };
  39789. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39790. if (this._scene) {
  39791. if (this._onKeyboardObserver) {
  39792. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39793. }
  39794. if (this._onCanvasBlurObserver) {
  39795. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39796. }
  39797. this._onKeyboardObserver = null;
  39798. this._onCanvasBlurObserver = null;
  39799. }
  39800. this._keys = [];
  39801. };
  39802. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39803. if (this._onKeyboardObserver) {
  39804. var camera = this.camera;
  39805. for (var index = 0; index < this._keys.length; index++) {
  39806. var keyCode = this._keys[index];
  39807. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39808. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39809. camera.inertialPanningX -= 1 / this.panningSensibility;
  39810. }
  39811. else {
  39812. camera.inertialAlphaOffset -= 0.01;
  39813. }
  39814. }
  39815. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39816. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39817. camera.inertialPanningY += 1 / this.panningSensibility;
  39818. }
  39819. else if (this._altPressed && this.useAltToZoom) {
  39820. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  39821. }
  39822. else {
  39823. camera.inertialBetaOffset -= 0.01;
  39824. }
  39825. }
  39826. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39827. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39828. camera.inertialPanningX += 1 / this.panningSensibility;
  39829. }
  39830. else {
  39831. camera.inertialAlphaOffset += 0.01;
  39832. }
  39833. }
  39834. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39835. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39836. camera.inertialPanningY -= 1 / this.panningSensibility;
  39837. }
  39838. else if (this._altPressed && this.useAltToZoom) {
  39839. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  39840. }
  39841. else {
  39842. camera.inertialBetaOffset += 0.01;
  39843. }
  39844. }
  39845. else if (this.keysReset.indexOf(keyCode) !== -1) {
  39846. camera.restoreState();
  39847. }
  39848. }
  39849. }
  39850. };
  39851. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  39852. return "ArcRotateCameraKeyboardMoveInput";
  39853. };
  39854. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39855. return "keyboard";
  39856. };
  39857. __decorate([
  39858. BABYLON.serialize()
  39859. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39860. __decorate([
  39861. BABYLON.serialize()
  39862. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39863. __decorate([
  39864. BABYLON.serialize()
  39865. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39866. __decorate([
  39867. BABYLON.serialize()
  39868. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39869. __decorate([
  39870. BABYLON.serialize()
  39871. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  39872. __decorate([
  39873. BABYLON.serialize()
  39874. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  39875. __decorate([
  39876. BABYLON.serialize()
  39877. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  39878. __decorate([
  39879. BABYLON.serialize()
  39880. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  39881. return ArcRotateCameraKeyboardMoveInput;
  39882. }());
  39883. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  39884. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  39885. })(BABYLON || (BABYLON = {}));
  39886. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  39887. var BABYLON;
  39888. (function (BABYLON) {
  39889. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  39890. function ArcRotateCameraMouseWheelInput() {
  39891. this.wheelPrecision = 3.0;
  39892. /**
  39893. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  39894. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  39895. */
  39896. this.wheelDeltaPercentage = 0;
  39897. }
  39898. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  39899. var _this = this;
  39900. this._wheel = function (p, s) {
  39901. //sanity check - this should be a PointerWheel event.
  39902. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  39903. return;
  39904. var event = p.event;
  39905. var delta = 0;
  39906. if (event.wheelDelta) {
  39907. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  39908. }
  39909. else if (event.detail) {
  39910. delta = -event.detail / _this.wheelPrecision;
  39911. }
  39912. if (delta)
  39913. _this.camera.inertialRadiusOffset += delta;
  39914. if (event.preventDefault) {
  39915. if (!noPreventDefault) {
  39916. event.preventDefault();
  39917. }
  39918. }
  39919. };
  39920. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  39921. };
  39922. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  39923. if (this._observer && element) {
  39924. this.camera.getScene().onPointerObservable.remove(this._observer);
  39925. this._observer = null;
  39926. this._wheel = null;
  39927. }
  39928. };
  39929. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  39930. return "ArcRotateCameraMouseWheelInput";
  39931. };
  39932. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  39933. return "mousewheel";
  39934. };
  39935. __decorate([
  39936. BABYLON.serialize()
  39937. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  39938. __decorate([
  39939. BABYLON.serialize()
  39940. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  39941. return ArcRotateCameraMouseWheelInput;
  39942. }());
  39943. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  39944. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  39945. })(BABYLON || (BABYLON = {}));
  39946. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  39947. var BABYLON;
  39948. (function (BABYLON) {
  39949. var ArcRotateCameraPointersInput = /** @class */ (function () {
  39950. function ArcRotateCameraPointersInput() {
  39951. this.buttons = [0, 1, 2];
  39952. this.angularSensibilityX = 1000.0;
  39953. this.angularSensibilityY = 1000.0;
  39954. this.pinchPrecision = 12.0;
  39955. /**
  39956. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  39957. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  39958. */
  39959. this.pinchDeltaPercentage = 0;
  39960. this.panningSensibility = 1000.0;
  39961. this.multiTouchPanning = true;
  39962. this.multiTouchPanAndZoom = true;
  39963. this._isPanClick = false;
  39964. this.pinchInwards = true;
  39965. }
  39966. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  39967. var _this = this;
  39968. var engine = this.camera.getEngine();
  39969. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  39970. var pointA = null;
  39971. var pointB = null;
  39972. var previousPinchSquaredDistance = 0;
  39973. var initialDistance = 0;
  39974. var twoFingerActivityCount = 0;
  39975. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  39976. this._pointerInput = function (p, s) {
  39977. var evt = p.event;
  39978. var isTouch = p.event.pointerType === "touch";
  39979. if (engine.isInVRExclusivePointerMode) {
  39980. return;
  39981. }
  39982. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39983. return;
  39984. }
  39985. var srcElement = (evt.srcElement || evt.target);
  39986. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  39987. try {
  39988. srcElement.setPointerCapture(evt.pointerId);
  39989. }
  39990. catch (e) {
  39991. //Nothing to do with the error. Execution will continue.
  39992. }
  39993. // Manage panning with pan button click
  39994. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  39995. // manage pointers
  39996. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  39997. if (pointA === null) {
  39998. pointA = cacheSoloPointer;
  39999. }
  40000. else if (pointB === null) {
  40001. pointB = cacheSoloPointer;
  40002. }
  40003. if (!noPreventDefault) {
  40004. evt.preventDefault();
  40005. element.focus();
  40006. }
  40007. }
  40008. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  40009. _this.camera.restoreState();
  40010. }
  40011. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  40012. try {
  40013. srcElement.releasePointerCapture(evt.pointerId);
  40014. }
  40015. catch (e) {
  40016. //Nothing to do with the error.
  40017. }
  40018. cacheSoloPointer = null;
  40019. previousPinchSquaredDistance = 0;
  40020. previousMultiTouchPanPosition.isPaning = false;
  40021. previousMultiTouchPanPosition.isPinching = false;
  40022. twoFingerActivityCount = 0;
  40023. initialDistance = 0;
  40024. if (!isTouch) {
  40025. pointB = null; // Mouse and pen are mono pointer
  40026. }
  40027. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  40028. //but emptying completly pointers collection is required to fix a bug on iPhone :
  40029. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  40030. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  40031. if (engine.badOS) {
  40032. pointA = pointB = null;
  40033. }
  40034. else {
  40035. //only remove the impacted pointer in case of multitouch allowing on most
  40036. //platforms switching from rotate to zoom and pan seamlessly.
  40037. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  40038. pointA = pointB;
  40039. pointB = null;
  40040. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  40041. }
  40042. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  40043. pointB = null;
  40044. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  40045. }
  40046. else {
  40047. pointA = pointB = null;
  40048. }
  40049. }
  40050. if (!noPreventDefault) {
  40051. evt.preventDefault();
  40052. }
  40053. }
  40054. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  40055. if (!noPreventDefault) {
  40056. evt.preventDefault();
  40057. }
  40058. // One button down
  40059. if (pointA && pointB === null && cacheSoloPointer) {
  40060. if (_this.panningSensibility !== 0 &&
  40061. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  40062. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  40063. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  40064. }
  40065. else {
  40066. var offsetX = evt.clientX - cacheSoloPointer.x;
  40067. var offsetY = evt.clientY - cacheSoloPointer.y;
  40068. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  40069. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  40070. }
  40071. cacheSoloPointer.x = evt.clientX;
  40072. cacheSoloPointer.y = evt.clientY;
  40073. }
  40074. else if (pointA && pointB) {
  40075. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  40076. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  40077. ed.x = evt.clientX;
  40078. ed.y = evt.clientY;
  40079. var direction = _this.pinchInwards ? 1 : -1;
  40080. var distX = pointA.x - pointB.x;
  40081. var distY = pointA.y - pointB.y;
  40082. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  40083. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  40084. if (previousPinchSquaredDistance === 0) {
  40085. initialDistance = pinchDistance;
  40086. previousPinchSquaredDistance = pinchSquaredDistance;
  40087. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  40088. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  40089. return;
  40090. }
  40091. if (_this.multiTouchPanAndZoom) {
  40092. if (_this.pinchDeltaPercentage) {
  40093. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  40094. }
  40095. else {
  40096. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  40097. (_this.pinchPrecision *
  40098. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  40099. direction);
  40100. }
  40101. if (_this.panningSensibility !== 0) {
  40102. var pointersCenterX = (pointA.x + pointB.x) / 2;
  40103. var pointersCenterY = (pointA.y + pointB.y) / 2;
  40104. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  40105. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  40106. previousMultiTouchPanPosition.x = pointersCenterX;
  40107. previousMultiTouchPanPosition.y = pointersCenterY;
  40108. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  40109. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  40110. }
  40111. }
  40112. else {
  40113. twoFingerActivityCount++;
  40114. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  40115. if (_this.pinchDeltaPercentage) {
  40116. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  40117. }
  40118. else {
  40119. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  40120. (_this.pinchPrecision *
  40121. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  40122. direction);
  40123. }
  40124. previousMultiTouchPanPosition.isPaning = false;
  40125. previousMultiTouchPanPosition.isPinching = true;
  40126. }
  40127. else {
  40128. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  40129. if (!previousMultiTouchPanPosition.isPaning) {
  40130. previousMultiTouchPanPosition.isPaning = true;
  40131. previousMultiTouchPanPosition.isPinching = false;
  40132. previousMultiTouchPanPosition.x = ed.x;
  40133. previousMultiTouchPanPosition.y = ed.y;
  40134. return;
  40135. }
  40136. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  40137. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  40138. }
  40139. }
  40140. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  40141. previousMultiTouchPanPosition.x = ed.x;
  40142. previousMultiTouchPanPosition.y = ed.y;
  40143. }
  40144. }
  40145. previousPinchSquaredDistance = pinchSquaredDistance;
  40146. }
  40147. }
  40148. };
  40149. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  40150. this._onContextMenu = function (evt) {
  40151. evt.preventDefault();
  40152. };
  40153. if (!this.camera._useCtrlForPanning) {
  40154. element.addEventListener("contextmenu", this._onContextMenu, false);
  40155. }
  40156. this._onLostFocus = function () {
  40157. //this._keys = [];
  40158. pointA = pointB = null;
  40159. previousPinchSquaredDistance = 0;
  40160. previousMultiTouchPanPosition.isPaning = false;
  40161. previousMultiTouchPanPosition.isPinching = false;
  40162. twoFingerActivityCount = 0;
  40163. cacheSoloPointer = null;
  40164. initialDistance = 0;
  40165. };
  40166. this._onMouseMove = function (evt) {
  40167. if (!engine.isPointerLock) {
  40168. return;
  40169. }
  40170. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  40171. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  40172. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  40173. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  40174. if (!noPreventDefault) {
  40175. evt.preventDefault();
  40176. }
  40177. };
  40178. this._onGestureStart = function (e) {
  40179. if (window.MSGesture === undefined) {
  40180. return;
  40181. }
  40182. if (!_this._MSGestureHandler) {
  40183. _this._MSGestureHandler = new MSGesture();
  40184. _this._MSGestureHandler.target = element;
  40185. }
  40186. _this._MSGestureHandler.addPointer(e.pointerId);
  40187. };
  40188. this._onGesture = function (e) {
  40189. _this.camera.radius *= e.scale;
  40190. if (e.preventDefault) {
  40191. if (!noPreventDefault) {
  40192. e.stopPropagation();
  40193. e.preventDefault();
  40194. }
  40195. }
  40196. };
  40197. element.addEventListener("mousemove", this._onMouseMove, false);
  40198. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  40199. element.addEventListener("MSGestureChange", this._onGesture, false);
  40200. BABYLON.Tools.RegisterTopRootEvents([
  40201. { name: "blur", handler: this._onLostFocus }
  40202. ]);
  40203. };
  40204. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  40205. if (this._onLostFocus) {
  40206. BABYLON.Tools.UnregisterTopRootEvents([
  40207. { name: "blur", handler: this._onLostFocus }
  40208. ]);
  40209. }
  40210. if (element && this._observer) {
  40211. this.camera.getScene().onPointerObservable.remove(this._observer);
  40212. this._observer = null;
  40213. if (this._onContextMenu) {
  40214. element.removeEventListener("contextmenu", this._onContextMenu);
  40215. }
  40216. if (this._onMouseMove) {
  40217. element.removeEventListener("mousemove", this._onMouseMove);
  40218. }
  40219. if (this._onGestureStart) {
  40220. element.removeEventListener("MSPointerDown", this._onGestureStart);
  40221. }
  40222. if (this._onGesture) {
  40223. element.removeEventListener("MSGestureChange", this._onGesture);
  40224. }
  40225. this._isPanClick = false;
  40226. this.pinchInwards = true;
  40227. this._onMouseMove = null;
  40228. this._onGestureStart = null;
  40229. this._onGesture = null;
  40230. this._MSGestureHandler = null;
  40231. this._onLostFocus = null;
  40232. this._onContextMenu = null;
  40233. }
  40234. };
  40235. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  40236. return "ArcRotateCameraPointersInput";
  40237. };
  40238. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  40239. return "pointers";
  40240. };
  40241. __decorate([
  40242. BABYLON.serialize()
  40243. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  40244. __decorate([
  40245. BABYLON.serialize()
  40246. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  40247. __decorate([
  40248. BABYLON.serialize()
  40249. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  40250. __decorate([
  40251. BABYLON.serialize()
  40252. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  40253. __decorate([
  40254. BABYLON.serialize()
  40255. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  40256. __decorate([
  40257. BABYLON.serialize()
  40258. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  40259. __decorate([
  40260. BABYLON.serialize()
  40261. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  40262. __decorate([
  40263. BABYLON.serialize()
  40264. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  40265. return ArcRotateCameraPointersInput;
  40266. }());
  40267. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  40268. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  40269. })(BABYLON || (BABYLON = {}));
  40270. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  40271. var BABYLON;
  40272. (function (BABYLON) {
  40273. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  40274. __extends(ArcRotateCameraInputsManager, _super);
  40275. function ArcRotateCameraInputsManager(camera) {
  40276. return _super.call(this, camera) || this;
  40277. }
  40278. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  40279. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  40280. return this;
  40281. };
  40282. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  40283. this.add(new BABYLON.ArcRotateCameraPointersInput());
  40284. return this;
  40285. };
  40286. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  40287. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  40288. return this;
  40289. };
  40290. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  40291. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  40292. return this;
  40293. };
  40294. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  40295. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  40296. return this;
  40297. };
  40298. return ArcRotateCameraInputsManager;
  40299. }(BABYLON.CameraInputsManager));
  40300. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  40301. })(BABYLON || (BABYLON = {}));
  40302. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  40303. var BABYLON;
  40304. (function (BABYLON) {
  40305. var ArcRotateCamera = /** @class */ (function (_super) {
  40306. __extends(ArcRotateCamera, _super);
  40307. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  40308. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  40309. _this.inertialAlphaOffset = 0;
  40310. _this.inertialBetaOffset = 0;
  40311. _this.inertialRadiusOffset = 0;
  40312. _this.lowerAlphaLimit = null;
  40313. _this.upperAlphaLimit = null;
  40314. _this.lowerBetaLimit = 0.01;
  40315. _this.upperBetaLimit = Math.PI;
  40316. _this.lowerRadiusLimit = null;
  40317. _this.upperRadiusLimit = null;
  40318. _this.inertialPanningX = 0;
  40319. _this.inertialPanningY = 0;
  40320. _this.pinchToPanMaxDistance = 20;
  40321. _this.panningDistanceLimit = null;
  40322. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  40323. _this.panningInertia = 0.9;
  40324. //-- end properties for backward compatibility for inputs
  40325. _this.zoomOnFactor = 1;
  40326. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  40327. _this.allowUpsideDown = true;
  40328. _this._viewMatrix = new BABYLON.Matrix();
  40329. // Panning
  40330. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  40331. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  40332. _this.checkCollisions = false;
  40333. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  40334. _this._previousPosition = BABYLON.Vector3.Zero();
  40335. _this._collisionVelocity = BABYLON.Vector3.Zero();
  40336. _this._newPosition = BABYLON.Vector3.Zero();
  40337. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  40338. if (collidedMesh === void 0) { collidedMesh = null; }
  40339. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  40340. newPosition.multiplyInPlace(_this._collider._radius);
  40341. }
  40342. if (!collidedMesh) {
  40343. _this._previousPosition.copyFrom(_this.position);
  40344. }
  40345. else {
  40346. _this.setPosition(newPosition);
  40347. if (_this.onCollide) {
  40348. _this.onCollide(collidedMesh);
  40349. }
  40350. }
  40351. // Recompute because of constraints
  40352. var cosa = Math.cos(_this.alpha);
  40353. var sina = Math.sin(_this.alpha);
  40354. var cosb = Math.cos(_this.beta);
  40355. var sinb = Math.sin(_this.beta);
  40356. if (sinb === 0) {
  40357. sinb = 0.0001;
  40358. }
  40359. var target = _this._getTargetPosition();
  40360. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  40361. _this.position.copyFrom(_this._newPosition);
  40362. var up = _this.upVector;
  40363. if (_this.allowUpsideDown && _this.beta < 0) {
  40364. up = up.clone();
  40365. up = up.negate();
  40366. }
  40367. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  40368. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  40369. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  40370. _this._collisionTriggered = false;
  40371. };
  40372. _this._target = BABYLON.Vector3.Zero();
  40373. if (target) {
  40374. _this.setTarget(target);
  40375. }
  40376. _this.alpha = alpha;
  40377. _this.beta = beta;
  40378. _this.radius = radius;
  40379. _this.getViewMatrix();
  40380. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  40381. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  40382. return _this;
  40383. }
  40384. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  40385. get: function () {
  40386. return this._target;
  40387. },
  40388. set: function (value) {
  40389. this.setTarget(value);
  40390. },
  40391. enumerable: true,
  40392. configurable: true
  40393. });
  40394. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  40395. //-- begin properties for backward compatibility for inputs
  40396. get: function () {
  40397. var pointers = this.inputs.attached["pointers"];
  40398. if (pointers)
  40399. return pointers.angularSensibilityX;
  40400. return 0;
  40401. },
  40402. set: function (value) {
  40403. var pointers = this.inputs.attached["pointers"];
  40404. if (pointers) {
  40405. pointers.angularSensibilityX = value;
  40406. }
  40407. },
  40408. enumerable: true,
  40409. configurable: true
  40410. });
  40411. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  40412. get: function () {
  40413. var pointers = this.inputs.attached["pointers"];
  40414. if (pointers)
  40415. return pointers.angularSensibilityY;
  40416. return 0;
  40417. },
  40418. set: function (value) {
  40419. var pointers = this.inputs.attached["pointers"];
  40420. if (pointers) {
  40421. pointers.angularSensibilityY = value;
  40422. }
  40423. },
  40424. enumerable: true,
  40425. configurable: true
  40426. });
  40427. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  40428. get: function () {
  40429. var pointers = this.inputs.attached["pointers"];
  40430. if (pointers)
  40431. return pointers.pinchPrecision;
  40432. return 0;
  40433. },
  40434. set: function (value) {
  40435. var pointers = this.inputs.attached["pointers"];
  40436. if (pointers) {
  40437. pointers.pinchPrecision = value;
  40438. }
  40439. },
  40440. enumerable: true,
  40441. configurable: true
  40442. });
  40443. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  40444. get: function () {
  40445. var pointers = this.inputs.attached["pointers"];
  40446. if (pointers)
  40447. return pointers.pinchDeltaPercentage;
  40448. return 0;
  40449. },
  40450. set: function (value) {
  40451. var pointers = this.inputs.attached["pointers"];
  40452. if (pointers) {
  40453. pointers.pinchDeltaPercentage = value;
  40454. }
  40455. },
  40456. enumerable: true,
  40457. configurable: true
  40458. });
  40459. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  40460. get: function () {
  40461. var pointers = this.inputs.attached["pointers"];
  40462. if (pointers)
  40463. return pointers.panningSensibility;
  40464. return 0;
  40465. },
  40466. set: function (value) {
  40467. var pointers = this.inputs.attached["pointers"];
  40468. if (pointers) {
  40469. pointers.panningSensibility = value;
  40470. }
  40471. },
  40472. enumerable: true,
  40473. configurable: true
  40474. });
  40475. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  40476. get: function () {
  40477. var keyboard = this.inputs.attached["keyboard"];
  40478. if (keyboard)
  40479. return keyboard.keysUp;
  40480. return [];
  40481. },
  40482. set: function (value) {
  40483. var keyboard = this.inputs.attached["keyboard"];
  40484. if (keyboard)
  40485. keyboard.keysUp = value;
  40486. },
  40487. enumerable: true,
  40488. configurable: true
  40489. });
  40490. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  40491. get: function () {
  40492. var keyboard = this.inputs.attached["keyboard"];
  40493. if (keyboard)
  40494. return keyboard.keysDown;
  40495. return [];
  40496. },
  40497. set: function (value) {
  40498. var keyboard = this.inputs.attached["keyboard"];
  40499. if (keyboard)
  40500. keyboard.keysDown = value;
  40501. },
  40502. enumerable: true,
  40503. configurable: true
  40504. });
  40505. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  40506. get: function () {
  40507. var keyboard = this.inputs.attached["keyboard"];
  40508. if (keyboard)
  40509. return keyboard.keysLeft;
  40510. return [];
  40511. },
  40512. set: function (value) {
  40513. var keyboard = this.inputs.attached["keyboard"];
  40514. if (keyboard)
  40515. keyboard.keysLeft = value;
  40516. },
  40517. enumerable: true,
  40518. configurable: true
  40519. });
  40520. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  40521. get: function () {
  40522. var keyboard = this.inputs.attached["keyboard"];
  40523. if (keyboard)
  40524. return keyboard.keysRight;
  40525. return [];
  40526. },
  40527. set: function (value) {
  40528. var keyboard = this.inputs.attached["keyboard"];
  40529. if (keyboard)
  40530. keyboard.keysRight = value;
  40531. },
  40532. enumerable: true,
  40533. configurable: true
  40534. });
  40535. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  40536. get: function () {
  40537. var mousewheel = this.inputs.attached["mousewheel"];
  40538. if (mousewheel)
  40539. return mousewheel.wheelPrecision;
  40540. return 0;
  40541. },
  40542. set: function (value) {
  40543. var mousewheel = this.inputs.attached["mousewheel"];
  40544. if (mousewheel)
  40545. mousewheel.wheelPrecision = value;
  40546. },
  40547. enumerable: true,
  40548. configurable: true
  40549. });
  40550. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  40551. get: function () {
  40552. var mousewheel = this.inputs.attached["mousewheel"];
  40553. if (mousewheel)
  40554. return mousewheel.wheelDeltaPercentage;
  40555. return 0;
  40556. },
  40557. set: function (value) {
  40558. var mousewheel = this.inputs.attached["mousewheel"];
  40559. if (mousewheel)
  40560. mousewheel.wheelDeltaPercentage = value;
  40561. },
  40562. enumerable: true,
  40563. configurable: true
  40564. });
  40565. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  40566. get: function () {
  40567. return this._bouncingBehavior;
  40568. },
  40569. enumerable: true,
  40570. configurable: true
  40571. });
  40572. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  40573. get: function () {
  40574. return this._bouncingBehavior != null;
  40575. },
  40576. set: function (value) {
  40577. if (value === this.useBouncingBehavior) {
  40578. return;
  40579. }
  40580. if (value) {
  40581. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  40582. this.addBehavior(this._bouncingBehavior);
  40583. }
  40584. else if (this._bouncingBehavior) {
  40585. this.removeBehavior(this._bouncingBehavior);
  40586. this._bouncingBehavior = null;
  40587. }
  40588. },
  40589. enumerable: true,
  40590. configurable: true
  40591. });
  40592. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  40593. get: function () {
  40594. return this._framingBehavior;
  40595. },
  40596. enumerable: true,
  40597. configurable: true
  40598. });
  40599. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  40600. get: function () {
  40601. return this._framingBehavior != null;
  40602. },
  40603. set: function (value) {
  40604. if (value === this.useFramingBehavior) {
  40605. return;
  40606. }
  40607. if (value) {
  40608. this._framingBehavior = new BABYLON.FramingBehavior();
  40609. this.addBehavior(this._framingBehavior);
  40610. }
  40611. else if (this._framingBehavior) {
  40612. this.removeBehavior(this._framingBehavior);
  40613. this._framingBehavior = null;
  40614. }
  40615. },
  40616. enumerable: true,
  40617. configurable: true
  40618. });
  40619. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  40620. get: function () {
  40621. return this._autoRotationBehavior;
  40622. },
  40623. enumerable: true,
  40624. configurable: true
  40625. });
  40626. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  40627. get: function () {
  40628. return this._autoRotationBehavior != null;
  40629. },
  40630. set: function (value) {
  40631. if (value === this.useAutoRotationBehavior) {
  40632. return;
  40633. }
  40634. if (value) {
  40635. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  40636. this.addBehavior(this._autoRotationBehavior);
  40637. }
  40638. else if (this._autoRotationBehavior) {
  40639. this.removeBehavior(this._autoRotationBehavior);
  40640. this._autoRotationBehavior = null;
  40641. }
  40642. },
  40643. enumerable: true,
  40644. configurable: true
  40645. });
  40646. // Cache
  40647. ArcRotateCamera.prototype._initCache = function () {
  40648. _super.prototype._initCache.call(this);
  40649. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40650. this._cache.alpha = undefined;
  40651. this._cache.beta = undefined;
  40652. this._cache.radius = undefined;
  40653. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  40654. };
  40655. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  40656. if (!ignoreParentClass) {
  40657. _super.prototype._updateCache.call(this);
  40658. }
  40659. this._cache._target.copyFrom(this._getTargetPosition());
  40660. this._cache.alpha = this.alpha;
  40661. this._cache.beta = this.beta;
  40662. this._cache.radius = this.radius;
  40663. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  40664. };
  40665. ArcRotateCamera.prototype._getTargetPosition = function () {
  40666. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  40667. var pos = this._targetHost.getAbsolutePosition();
  40668. if (this._targetBoundingCenter) {
  40669. pos.addToRef(this._targetBoundingCenter, this._target);
  40670. }
  40671. else {
  40672. this._target.copyFrom(pos);
  40673. }
  40674. }
  40675. var lockedTargetPosition = this._getLockedTargetPosition();
  40676. if (lockedTargetPosition) {
  40677. return lockedTargetPosition;
  40678. }
  40679. return this._target;
  40680. };
  40681. ArcRotateCamera.prototype.storeState = function () {
  40682. this._storedAlpha = this.alpha;
  40683. this._storedBeta = this.beta;
  40684. this._storedRadius = this.radius;
  40685. this._storedTarget = this._getTargetPosition().clone();
  40686. return _super.prototype.storeState.call(this);
  40687. };
  40688. /**
  40689. * Restored camera state. You must call storeState() first
  40690. */
  40691. ArcRotateCamera.prototype._restoreStateValues = function () {
  40692. if (!_super.prototype._restoreStateValues.call(this)) {
  40693. return false;
  40694. }
  40695. this.alpha = this._storedAlpha;
  40696. this.beta = this._storedBeta;
  40697. this.radius = this._storedRadius;
  40698. this.setTarget(this._storedTarget.clone());
  40699. this.inertialAlphaOffset = 0;
  40700. this.inertialBetaOffset = 0;
  40701. this.inertialRadiusOffset = 0;
  40702. this.inertialPanningX = 0;
  40703. this.inertialPanningY = 0;
  40704. return true;
  40705. };
  40706. // Synchronized
  40707. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  40708. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  40709. return false;
  40710. return this._cache._target.equals(this._getTargetPosition())
  40711. && this._cache.alpha === this.alpha
  40712. && this._cache.beta === this.beta
  40713. && this._cache.radius === this.radius
  40714. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  40715. };
  40716. // Methods
  40717. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  40718. var _this = this;
  40719. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  40720. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  40721. this._useCtrlForPanning = useCtrlForPanning;
  40722. this._panningMouseButton = panningMouseButton;
  40723. this.inputs.attachElement(element, noPreventDefault);
  40724. this._reset = function () {
  40725. _this.inertialAlphaOffset = 0;
  40726. _this.inertialBetaOffset = 0;
  40727. _this.inertialRadiusOffset = 0;
  40728. _this.inertialPanningX = 0;
  40729. _this.inertialPanningY = 0;
  40730. };
  40731. };
  40732. ArcRotateCamera.prototype.detachControl = function (element) {
  40733. this.inputs.detachElement(element);
  40734. if (this._reset) {
  40735. this._reset();
  40736. }
  40737. };
  40738. ArcRotateCamera.prototype._checkInputs = function () {
  40739. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  40740. if (this._collisionTriggered) {
  40741. return;
  40742. }
  40743. this.inputs.checkInputs();
  40744. // Inertia
  40745. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  40746. if (this.getScene().useRightHandedSystem) {
  40747. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40748. }
  40749. else {
  40750. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40751. }
  40752. this.beta += this.inertialBetaOffset;
  40753. this.radius -= this.inertialRadiusOffset;
  40754. this.inertialAlphaOffset *= this.inertia;
  40755. this.inertialBetaOffset *= this.inertia;
  40756. this.inertialRadiusOffset *= this.inertia;
  40757. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  40758. this.inertialAlphaOffset = 0;
  40759. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  40760. this.inertialBetaOffset = 0;
  40761. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  40762. this.inertialRadiusOffset = 0;
  40763. }
  40764. // Panning inertia
  40765. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  40766. if (!this._localDirection) {
  40767. this._localDirection = BABYLON.Vector3.Zero();
  40768. this._transformedDirection = BABYLON.Vector3.Zero();
  40769. }
  40770. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  40771. this._localDirection.multiplyInPlace(this.panningAxis);
  40772. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  40773. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  40774. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  40775. if (!this.panningAxis.y) {
  40776. this._transformedDirection.y = 0;
  40777. }
  40778. if (!this._targetHost) {
  40779. if (this.panningDistanceLimit) {
  40780. this._transformedDirection.addInPlace(this._target);
  40781. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  40782. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  40783. this._target.copyFrom(this._transformedDirection);
  40784. }
  40785. }
  40786. else {
  40787. this._target.addInPlace(this._transformedDirection);
  40788. }
  40789. }
  40790. this.inertialPanningX *= this.panningInertia;
  40791. this.inertialPanningY *= this.panningInertia;
  40792. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  40793. this.inertialPanningX = 0;
  40794. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  40795. this.inertialPanningY = 0;
  40796. }
  40797. // Limits
  40798. this._checkLimits();
  40799. _super.prototype._checkInputs.call(this);
  40800. };
  40801. ArcRotateCamera.prototype._checkLimits = function () {
  40802. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  40803. if (this.allowUpsideDown && this.beta > Math.PI) {
  40804. this.beta = this.beta - (2 * Math.PI);
  40805. }
  40806. }
  40807. else {
  40808. if (this.beta < this.lowerBetaLimit) {
  40809. this.beta = this.lowerBetaLimit;
  40810. }
  40811. }
  40812. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  40813. if (this.allowUpsideDown && this.beta < -Math.PI) {
  40814. this.beta = this.beta + (2 * Math.PI);
  40815. }
  40816. }
  40817. else {
  40818. if (this.beta > this.upperBetaLimit) {
  40819. this.beta = this.upperBetaLimit;
  40820. }
  40821. }
  40822. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  40823. this.alpha = this.lowerAlphaLimit;
  40824. }
  40825. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  40826. this.alpha = this.upperAlphaLimit;
  40827. }
  40828. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  40829. this.radius = this.lowerRadiusLimit;
  40830. }
  40831. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  40832. this.radius = this.upperRadiusLimit;
  40833. }
  40834. };
  40835. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  40836. var radiusv3 = this.position.subtract(this._getTargetPosition());
  40837. this.radius = radiusv3.length();
  40838. if (this.radius === 0) {
  40839. this.radius = 0.0001; // Just to avoid division by zero
  40840. }
  40841. // Alpha
  40842. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  40843. if (radiusv3.z < 0) {
  40844. this.alpha = 2 * Math.PI - this.alpha;
  40845. }
  40846. // Beta
  40847. this.beta = Math.acos(radiusv3.y / this.radius);
  40848. this._checkLimits();
  40849. };
  40850. ArcRotateCamera.prototype.setPosition = function (position) {
  40851. if (this.position.equals(position)) {
  40852. return;
  40853. }
  40854. this.position.copyFrom(position);
  40855. this.rebuildAnglesAndRadius();
  40856. };
  40857. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  40858. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  40859. if (allowSamePosition === void 0) { allowSamePosition = false; }
  40860. if (target.getBoundingInfo) {
  40861. if (toBoundingCenter) {
  40862. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  40863. }
  40864. else {
  40865. this._targetBoundingCenter = null;
  40866. }
  40867. this._targetHost = target;
  40868. this._target = this._getTargetPosition();
  40869. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  40870. }
  40871. else {
  40872. var newTarget = target;
  40873. var currentTarget = this._getTargetPosition();
  40874. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  40875. return;
  40876. }
  40877. this._targetHost = null;
  40878. this._target = newTarget;
  40879. this._targetBoundingCenter = null;
  40880. this.onMeshTargetChangedObservable.notifyObservers(null);
  40881. }
  40882. this.rebuildAnglesAndRadius();
  40883. };
  40884. ArcRotateCamera.prototype._getViewMatrix = function () {
  40885. // Compute
  40886. var cosa = Math.cos(this.alpha);
  40887. var sina = Math.sin(this.alpha);
  40888. var cosb = Math.cos(this.beta);
  40889. var sinb = Math.sin(this.beta);
  40890. if (sinb === 0) {
  40891. sinb = 0.0001;
  40892. }
  40893. var target = this._getTargetPosition();
  40894. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  40895. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  40896. if (!this._collider) {
  40897. this._collider = new BABYLON.Collider();
  40898. }
  40899. this._collider._radius = this.collisionRadius;
  40900. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  40901. this._collisionTriggered = true;
  40902. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40903. }
  40904. else {
  40905. this.position.copyFrom(this._newPosition);
  40906. var up = this.upVector;
  40907. if (this.allowUpsideDown && sinb < 0) {
  40908. up = up.clone();
  40909. up = up.negate();
  40910. }
  40911. if (this.getScene().useRightHandedSystem) {
  40912. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  40913. }
  40914. else {
  40915. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  40916. }
  40917. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  40918. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  40919. }
  40920. this._currentTarget = target;
  40921. return this._viewMatrix;
  40922. };
  40923. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  40924. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40925. meshes = meshes || this.getScene().meshes;
  40926. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  40927. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  40928. this.radius = distance * this.zoomOnFactor;
  40929. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  40930. };
  40931. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  40932. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40933. var meshesOrMinMaxVector;
  40934. var distance;
  40935. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  40936. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  40937. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  40938. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  40939. }
  40940. else {
  40941. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  40942. meshesOrMinMaxVector = minMaxVectorAndDistance;
  40943. distance = minMaxVectorAndDistance.distance;
  40944. }
  40945. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  40946. if (!doNotUpdateMaxZ) {
  40947. this.maxZ = distance * 2;
  40948. }
  40949. };
  40950. /**
  40951. * @override
  40952. * Override Camera.createRigCamera
  40953. */
  40954. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40955. var alphaShift = 0;
  40956. switch (this.cameraRigMode) {
  40957. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40958. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40959. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40960. case BABYLON.Camera.RIG_MODE_VR:
  40961. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  40962. break;
  40963. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40964. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  40965. break;
  40966. }
  40967. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  40968. rigCam._cameraRigParams = {};
  40969. return rigCam;
  40970. };
  40971. /**
  40972. * @override
  40973. * Override Camera._updateRigCameras
  40974. */
  40975. ArcRotateCamera.prototype._updateRigCameras = function () {
  40976. var camLeft = this._rigCameras[0];
  40977. var camRight = this._rigCameras[1];
  40978. camLeft.beta = camRight.beta = this.beta;
  40979. camLeft.radius = camRight.radius = this.radius;
  40980. switch (this.cameraRigMode) {
  40981. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40982. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40983. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40984. case BABYLON.Camera.RIG_MODE_VR:
  40985. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  40986. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  40987. break;
  40988. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40989. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  40990. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  40991. break;
  40992. }
  40993. _super.prototype._updateRigCameras.call(this);
  40994. };
  40995. ArcRotateCamera.prototype.dispose = function () {
  40996. this.inputs.clear();
  40997. _super.prototype.dispose.call(this);
  40998. };
  40999. ArcRotateCamera.prototype.getClassName = function () {
  41000. return "ArcRotateCamera";
  41001. };
  41002. __decorate([
  41003. BABYLON.serialize()
  41004. ], ArcRotateCamera.prototype, "alpha", void 0);
  41005. __decorate([
  41006. BABYLON.serialize()
  41007. ], ArcRotateCamera.prototype, "beta", void 0);
  41008. __decorate([
  41009. BABYLON.serialize()
  41010. ], ArcRotateCamera.prototype, "radius", void 0);
  41011. __decorate([
  41012. BABYLON.serializeAsVector3("target")
  41013. ], ArcRotateCamera.prototype, "_target", void 0);
  41014. __decorate([
  41015. BABYLON.serialize()
  41016. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  41017. __decorate([
  41018. BABYLON.serialize()
  41019. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  41020. __decorate([
  41021. BABYLON.serialize()
  41022. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  41023. __decorate([
  41024. BABYLON.serialize()
  41025. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  41026. __decorate([
  41027. BABYLON.serialize()
  41028. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  41029. __decorate([
  41030. BABYLON.serialize()
  41031. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  41032. __decorate([
  41033. BABYLON.serialize()
  41034. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  41035. __decorate([
  41036. BABYLON.serialize()
  41037. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  41038. __decorate([
  41039. BABYLON.serialize()
  41040. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  41041. __decorate([
  41042. BABYLON.serialize()
  41043. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  41044. __decorate([
  41045. BABYLON.serialize()
  41046. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  41047. __decorate([
  41048. BABYLON.serialize()
  41049. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  41050. __decorate([
  41051. BABYLON.serialize()
  41052. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  41053. __decorate([
  41054. BABYLON.serializeAsVector3()
  41055. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  41056. __decorate([
  41057. BABYLON.serialize()
  41058. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  41059. __decorate([
  41060. BABYLON.serialize()
  41061. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  41062. __decorate([
  41063. BABYLON.serialize()
  41064. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  41065. return ArcRotateCamera;
  41066. }(BABYLON.TargetCamera));
  41067. BABYLON.ArcRotateCamera = ArcRotateCamera;
  41068. })(BABYLON || (BABYLON = {}));
  41069. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  41070. var BABYLON;
  41071. (function (BABYLON) {
  41072. var HemisphericLight = /** @class */ (function (_super) {
  41073. __extends(HemisphericLight, _super);
  41074. /**
  41075. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  41076. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  41077. * The HemisphericLight can't cast shadows.
  41078. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41079. */
  41080. function HemisphericLight(name, direction, scene) {
  41081. var _this = _super.call(this, name, scene) || this;
  41082. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  41083. _this.direction = direction || BABYLON.Vector3.Up();
  41084. return _this;
  41085. }
  41086. HemisphericLight.prototype._buildUniformLayout = function () {
  41087. this._uniformBuffer.addUniform("vLightData", 4);
  41088. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41089. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41090. this._uniformBuffer.addUniform("vLightGround", 3);
  41091. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41092. this._uniformBuffer.addUniform("depthValues", 2);
  41093. this._uniformBuffer.create();
  41094. };
  41095. /**
  41096. * Returns the string "HemisphericLight".
  41097. */
  41098. HemisphericLight.prototype.getClassName = function () {
  41099. return "HemisphericLight";
  41100. };
  41101. /**
  41102. * Sets the HemisphericLight direction towards the passed target (Vector3).
  41103. * Returns the updated direction.
  41104. */
  41105. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  41106. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  41107. return this.direction;
  41108. };
  41109. HemisphericLight.prototype.getShadowGenerator = function () {
  41110. return null;
  41111. };
  41112. /**
  41113. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  41114. * Returns the HemisphericLight.
  41115. */
  41116. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  41117. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41118. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  41119. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  41120. return this;
  41121. };
  41122. HemisphericLight.prototype._getWorldMatrix = function () {
  41123. if (!this._worldMatrix) {
  41124. this._worldMatrix = BABYLON.Matrix.Identity();
  41125. }
  41126. return this._worldMatrix;
  41127. };
  41128. /**
  41129. * Returns the integer 3.
  41130. */
  41131. HemisphericLight.prototype.getTypeID = function () {
  41132. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  41133. };
  41134. __decorate([
  41135. BABYLON.serializeAsColor3()
  41136. ], HemisphericLight.prototype, "groundColor", void 0);
  41137. __decorate([
  41138. BABYLON.serializeAsVector3()
  41139. ], HemisphericLight.prototype, "direction", void 0);
  41140. return HemisphericLight;
  41141. }(BABYLON.Light));
  41142. BABYLON.HemisphericLight = HemisphericLight;
  41143. })(BABYLON || (BABYLON = {}));
  41144. //# sourceMappingURL=babylon.hemisphericLight.js.map
  41145. var BABYLON;
  41146. (function (BABYLON) {
  41147. var ShadowLight = /** @class */ (function (_super) {
  41148. __extends(ShadowLight, _super);
  41149. function ShadowLight() {
  41150. var _this = _super !== null && _super.apply(this, arguments) || this;
  41151. _this._needProjectionMatrixCompute = true;
  41152. return _this;
  41153. }
  41154. Object.defineProperty(ShadowLight.prototype, "direction", {
  41155. get: function () {
  41156. return this._direction;
  41157. },
  41158. set: function (value) {
  41159. this._direction = value;
  41160. },
  41161. enumerable: true,
  41162. configurable: true
  41163. });
  41164. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  41165. get: function () {
  41166. return this._shadowMinZ;
  41167. },
  41168. set: function (value) {
  41169. this._shadowMinZ = value;
  41170. this.forceProjectionMatrixCompute();
  41171. },
  41172. enumerable: true,
  41173. configurable: true
  41174. });
  41175. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  41176. get: function () {
  41177. return this._shadowMaxZ;
  41178. },
  41179. set: function (value) {
  41180. this._shadowMaxZ = value;
  41181. this.forceProjectionMatrixCompute();
  41182. },
  41183. enumerable: true,
  41184. configurable: true
  41185. });
  41186. /**
  41187. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  41188. */
  41189. ShadowLight.prototype.computeTransformedInformation = function () {
  41190. if (this.parent && this.parent.getWorldMatrix) {
  41191. if (!this.transformedPosition) {
  41192. this.transformedPosition = BABYLON.Vector3.Zero();
  41193. }
  41194. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  41195. // In case the direction is present.
  41196. if (this.direction) {
  41197. if (!this.transformedDirection) {
  41198. this.transformedDirection = BABYLON.Vector3.Zero();
  41199. }
  41200. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  41201. }
  41202. return true;
  41203. }
  41204. return false;
  41205. };
  41206. /**
  41207. * Return the depth scale used for the shadow map.
  41208. */
  41209. ShadowLight.prototype.getDepthScale = function () {
  41210. return 50.0;
  41211. };
  41212. /**
  41213. * Returns the light direction (Vector3) for any passed face index.
  41214. */
  41215. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  41216. return this.transformedDirection ? this.transformedDirection : this.direction;
  41217. };
  41218. /**
  41219. * Returns the ShadowLight absolute position in the World.
  41220. */
  41221. ShadowLight.prototype.getAbsolutePosition = function () {
  41222. return this.transformedPosition ? this.transformedPosition : this.position;
  41223. };
  41224. /**
  41225. * Sets the ShadowLight direction toward the passed target (Vector3).
  41226. * Returns the updated ShadowLight direction (Vector3).
  41227. */
  41228. ShadowLight.prototype.setDirectionToTarget = function (target) {
  41229. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  41230. return this.direction;
  41231. };
  41232. /**
  41233. * Returns the light rotation (Vector3).
  41234. */
  41235. ShadowLight.prototype.getRotation = function () {
  41236. this.direction.normalize();
  41237. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  41238. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  41239. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  41240. };
  41241. /**
  41242. * Boolean : false by default.
  41243. */
  41244. ShadowLight.prototype.needCube = function () {
  41245. return false;
  41246. };
  41247. /**
  41248. * Specifies wether or not the projection matrix should be recomputed this frame.
  41249. */
  41250. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  41251. return this._needProjectionMatrixCompute;
  41252. };
  41253. /**
  41254. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  41255. */
  41256. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  41257. this._needProjectionMatrixCompute = true;
  41258. };
  41259. /**
  41260. * Get the world matrix of the sahdow lights.
  41261. */
  41262. ShadowLight.prototype._getWorldMatrix = function () {
  41263. if (!this._worldMatrix) {
  41264. this._worldMatrix = BABYLON.Matrix.Identity();
  41265. }
  41266. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  41267. return this._worldMatrix;
  41268. };
  41269. /**
  41270. * Gets the minZ used for shadow according to both the scene and the light.
  41271. * @param activeCamera
  41272. */
  41273. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  41274. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  41275. };
  41276. /**
  41277. * Gets the maxZ used for shadow according to both the scene and the light.
  41278. * @param activeCamera
  41279. */
  41280. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  41281. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  41282. };
  41283. /**
  41284. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  41285. * Returns the light.
  41286. */
  41287. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41288. if (this.customProjectionMatrixBuilder) {
  41289. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  41290. }
  41291. else {
  41292. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  41293. }
  41294. return this;
  41295. };
  41296. __decorate([
  41297. BABYLON.serializeAsVector3()
  41298. ], ShadowLight.prototype, "position", void 0);
  41299. __decorate([
  41300. BABYLON.serializeAsVector3()
  41301. ], ShadowLight.prototype, "direction", null);
  41302. __decorate([
  41303. BABYLON.serialize()
  41304. ], ShadowLight.prototype, "shadowMinZ", null);
  41305. __decorate([
  41306. BABYLON.serialize()
  41307. ], ShadowLight.prototype, "shadowMaxZ", null);
  41308. return ShadowLight;
  41309. }(BABYLON.Light));
  41310. BABYLON.ShadowLight = ShadowLight;
  41311. })(BABYLON || (BABYLON = {}));
  41312. //# sourceMappingURL=babylon.shadowLight.js.map
  41313. var BABYLON;
  41314. (function (BABYLON) {
  41315. var PointLight = /** @class */ (function (_super) {
  41316. __extends(PointLight, _super);
  41317. /**
  41318. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  41319. * A PointLight emits the light in every direction.
  41320. * It can cast shadows.
  41321. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  41322. * ```javascript
  41323. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  41324. * ```
  41325. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41326. */
  41327. function PointLight(name, position, scene) {
  41328. var _this = _super.call(this, name, scene) || this;
  41329. _this._shadowAngle = Math.PI / 2;
  41330. _this.position = position;
  41331. return _this;
  41332. }
  41333. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  41334. /**
  41335. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41336. * This specifies what angle the shadow will use to be created.
  41337. *
  41338. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  41339. */
  41340. get: function () {
  41341. return this._shadowAngle;
  41342. },
  41343. /**
  41344. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41345. * This specifies what angle the shadow will use to be created.
  41346. *
  41347. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  41348. */
  41349. set: function (value) {
  41350. this._shadowAngle = value;
  41351. this.forceProjectionMatrixCompute();
  41352. },
  41353. enumerable: true,
  41354. configurable: true
  41355. });
  41356. Object.defineProperty(PointLight.prototype, "direction", {
  41357. get: function () {
  41358. return this._direction;
  41359. },
  41360. /**
  41361. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41362. */
  41363. set: function (value) {
  41364. var previousNeedCube = this.needCube();
  41365. this._direction = value;
  41366. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  41367. this._shadowGenerator.recreateShadowMap();
  41368. }
  41369. },
  41370. enumerable: true,
  41371. configurable: true
  41372. });
  41373. /**
  41374. * Returns the string "PointLight"
  41375. */
  41376. PointLight.prototype.getClassName = function () {
  41377. return "PointLight";
  41378. };
  41379. /**
  41380. * Returns the integer 0.
  41381. */
  41382. PointLight.prototype.getTypeID = function () {
  41383. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  41384. };
  41385. /**
  41386. * Specifies wether or not the shadowmap should be a cube texture.
  41387. */
  41388. PointLight.prototype.needCube = function () {
  41389. return !this.direction;
  41390. };
  41391. /**
  41392. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  41393. */
  41394. PointLight.prototype.getShadowDirection = function (faceIndex) {
  41395. if (this.direction) {
  41396. return _super.prototype.getShadowDirection.call(this, faceIndex);
  41397. }
  41398. else {
  41399. switch (faceIndex) {
  41400. case 0:
  41401. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  41402. case 1:
  41403. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  41404. case 2:
  41405. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  41406. case 3:
  41407. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  41408. case 4:
  41409. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  41410. case 5:
  41411. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  41412. }
  41413. }
  41414. return BABYLON.Vector3.Zero();
  41415. };
  41416. /**
  41417. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  41418. * - fov = PI / 2
  41419. * - aspect ratio : 1.0
  41420. * - z-near and far equal to the active camera minZ and maxZ.
  41421. * Returns the PointLight.
  41422. */
  41423. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41424. var activeCamera = this.getScene().activeCamera;
  41425. if (!activeCamera) {
  41426. return;
  41427. }
  41428. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41429. };
  41430. PointLight.prototype._buildUniformLayout = function () {
  41431. this._uniformBuffer.addUniform("vLightData", 4);
  41432. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41433. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41434. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41435. this._uniformBuffer.addUniform("depthValues", 2);
  41436. this._uniformBuffer.create();
  41437. };
  41438. /**
  41439. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  41440. * Returns the PointLight.
  41441. */
  41442. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  41443. if (this.computeTransformedInformation()) {
  41444. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  41445. return this;
  41446. }
  41447. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  41448. return this;
  41449. };
  41450. __decorate([
  41451. BABYLON.serialize()
  41452. ], PointLight.prototype, "shadowAngle", null);
  41453. return PointLight;
  41454. }(BABYLON.ShadowLight));
  41455. BABYLON.PointLight = PointLight;
  41456. })(BABYLON || (BABYLON = {}));
  41457. //# sourceMappingURL=babylon.pointLight.js.map
  41458. var BABYLON;
  41459. (function (BABYLON) {
  41460. var DirectionalLight = /** @class */ (function (_super) {
  41461. __extends(DirectionalLight, _super);
  41462. /**
  41463. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  41464. * The directional light is emitted from everywhere in the given direction.
  41465. * It can cast shawdows.
  41466. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41467. */
  41468. function DirectionalLight(name, direction, scene) {
  41469. var _this = _super.call(this, name, scene) || this;
  41470. _this._shadowFrustumSize = 0;
  41471. _this._shadowOrthoScale = 0.5;
  41472. _this.autoUpdateExtends = true;
  41473. // Cache
  41474. _this._orthoLeft = Number.MAX_VALUE;
  41475. _this._orthoRight = Number.MIN_VALUE;
  41476. _this._orthoTop = Number.MIN_VALUE;
  41477. _this._orthoBottom = Number.MAX_VALUE;
  41478. _this.position = direction.scale(-1.0);
  41479. _this.direction = direction;
  41480. return _this;
  41481. }
  41482. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  41483. /**
  41484. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  41485. */
  41486. get: function () {
  41487. return this._shadowFrustumSize;
  41488. },
  41489. /**
  41490. * Specifies a fix frustum size for the shadow generation.
  41491. */
  41492. set: function (value) {
  41493. this._shadowFrustumSize = value;
  41494. this.forceProjectionMatrixCompute();
  41495. },
  41496. enumerable: true,
  41497. configurable: true
  41498. });
  41499. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  41500. get: function () {
  41501. return this._shadowOrthoScale;
  41502. },
  41503. set: function (value) {
  41504. this._shadowOrthoScale = value;
  41505. this.forceProjectionMatrixCompute();
  41506. },
  41507. enumerable: true,
  41508. configurable: true
  41509. });
  41510. /**
  41511. * Returns the string "DirectionalLight".
  41512. */
  41513. DirectionalLight.prototype.getClassName = function () {
  41514. return "DirectionalLight";
  41515. };
  41516. /**
  41517. * Returns the integer 1.
  41518. */
  41519. DirectionalLight.prototype.getTypeID = function () {
  41520. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  41521. };
  41522. /**
  41523. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  41524. * Returns the DirectionalLight Shadow projection matrix.
  41525. */
  41526. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41527. if (this.shadowFrustumSize > 0) {
  41528. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  41529. }
  41530. else {
  41531. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  41532. }
  41533. };
  41534. /**
  41535. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  41536. * Returns the DirectionalLight Shadow projection matrix.
  41537. */
  41538. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  41539. var activeCamera = this.getScene().activeCamera;
  41540. if (!activeCamera) {
  41541. return;
  41542. }
  41543. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  41544. };
  41545. /**
  41546. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  41547. * Returns the DirectionalLight Shadow projection matrix.
  41548. */
  41549. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41550. var activeCamera = this.getScene().activeCamera;
  41551. if (!activeCamera) {
  41552. return;
  41553. }
  41554. // Check extends
  41555. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  41556. var tempVector3 = BABYLON.Vector3.Zero();
  41557. this._orthoLeft = Number.MAX_VALUE;
  41558. this._orthoRight = Number.MIN_VALUE;
  41559. this._orthoTop = Number.MIN_VALUE;
  41560. this._orthoBottom = Number.MAX_VALUE;
  41561. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  41562. var mesh = renderList[meshIndex];
  41563. if (!mesh) {
  41564. continue;
  41565. }
  41566. var boundingInfo = mesh.getBoundingInfo();
  41567. var boundingBox = boundingInfo.boundingBox;
  41568. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  41569. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  41570. if (tempVector3.x < this._orthoLeft)
  41571. this._orthoLeft = tempVector3.x;
  41572. if (tempVector3.y < this._orthoBottom)
  41573. this._orthoBottom = tempVector3.y;
  41574. if (tempVector3.x > this._orthoRight)
  41575. this._orthoRight = tempVector3.x;
  41576. if (tempVector3.y > this._orthoTop)
  41577. this._orthoTop = tempVector3.y;
  41578. }
  41579. }
  41580. }
  41581. var xOffset = this._orthoRight - this._orthoLeft;
  41582. var yOffset = this._orthoTop - this._orthoBottom;
  41583. 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);
  41584. };
  41585. DirectionalLight.prototype._buildUniformLayout = function () {
  41586. this._uniformBuffer.addUniform("vLightData", 4);
  41587. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41588. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41589. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41590. this._uniformBuffer.addUniform("depthValues", 2);
  41591. this._uniformBuffer.create();
  41592. };
  41593. /**
  41594. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  41595. * Returns the DirectionalLight.
  41596. */
  41597. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  41598. if (this.computeTransformedInformation()) {
  41599. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  41600. return this;
  41601. }
  41602. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  41603. return this;
  41604. };
  41605. /**
  41606. * Gets the minZ used for shadow according to both the scene and the light.
  41607. *
  41608. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41609. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41610. * @param activeCamera
  41611. */
  41612. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  41613. return 1;
  41614. };
  41615. /**
  41616. * Gets the maxZ used for shadow according to both the scene and the light.
  41617. *
  41618. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41619. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41620. * @param activeCamera
  41621. */
  41622. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  41623. return 1;
  41624. };
  41625. __decorate([
  41626. BABYLON.serialize()
  41627. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  41628. __decorate([
  41629. BABYLON.serialize()
  41630. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  41631. __decorate([
  41632. BABYLON.serialize()
  41633. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  41634. return DirectionalLight;
  41635. }(BABYLON.ShadowLight));
  41636. BABYLON.DirectionalLight = DirectionalLight;
  41637. })(BABYLON || (BABYLON = {}));
  41638. //# sourceMappingURL=babylon.directionalLight.js.map
  41639. var BABYLON;
  41640. (function (BABYLON) {
  41641. var SpotLight = /** @class */ (function (_super) {
  41642. __extends(SpotLight, _super);
  41643. /**
  41644. * Creates a SpotLight object in the scene with the passed parameters :
  41645. * - `position` (Vector3) is the initial SpotLight position,
  41646. * - `direction` (Vector3) is the initial SpotLight direction,
  41647. * - `angle` (float, in radians) is the spot light cone angle,
  41648. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  41649. * A spot light is a simply light oriented cone.
  41650. * It can cast shadows.
  41651. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41652. */
  41653. function SpotLight(name, position, direction, angle, exponent, scene) {
  41654. var _this = _super.call(this, name, scene) || this;
  41655. _this.position = position;
  41656. _this.direction = direction;
  41657. _this.angle = angle;
  41658. _this.exponent = exponent;
  41659. return _this;
  41660. }
  41661. Object.defineProperty(SpotLight.prototype, "angle", {
  41662. get: function () {
  41663. return this._angle;
  41664. },
  41665. set: function (value) {
  41666. this._angle = value;
  41667. this.forceProjectionMatrixCompute();
  41668. },
  41669. enumerable: true,
  41670. configurable: true
  41671. });
  41672. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  41673. get: function () {
  41674. return this._shadowAngleScale;
  41675. },
  41676. /**
  41677. * Allows scaling the angle of the light for shadow generation only.
  41678. */
  41679. set: function (value) {
  41680. this._shadowAngleScale = value;
  41681. this.forceProjectionMatrixCompute();
  41682. },
  41683. enumerable: true,
  41684. configurable: true
  41685. });
  41686. /**
  41687. * Returns the string "SpotLight".
  41688. */
  41689. SpotLight.prototype.getClassName = function () {
  41690. return "SpotLight";
  41691. };
  41692. /**
  41693. * Returns the integer 2.
  41694. */
  41695. SpotLight.prototype.getTypeID = function () {
  41696. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  41697. };
  41698. /**
  41699. * 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.
  41700. * Returns the SpotLight.
  41701. */
  41702. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41703. var activeCamera = this.getScene().activeCamera;
  41704. if (!activeCamera) {
  41705. return;
  41706. }
  41707. this._shadowAngleScale = this._shadowAngleScale || 1;
  41708. var angle = this._shadowAngleScale * this._angle;
  41709. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41710. };
  41711. SpotLight.prototype._buildUniformLayout = function () {
  41712. this._uniformBuffer.addUniform("vLightData", 4);
  41713. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41714. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41715. this._uniformBuffer.addUniform("vLightDirection", 3);
  41716. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41717. this._uniformBuffer.addUniform("depthValues", 2);
  41718. this._uniformBuffer.create();
  41719. };
  41720. /**
  41721. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  41722. * Return the SpotLight.
  41723. */
  41724. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  41725. var normalizeDirection;
  41726. if (this.computeTransformedInformation()) {
  41727. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  41728. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  41729. }
  41730. else {
  41731. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  41732. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41733. }
  41734. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  41735. return this;
  41736. };
  41737. __decorate([
  41738. BABYLON.serialize()
  41739. ], SpotLight.prototype, "angle", null);
  41740. __decorate([
  41741. BABYLON.serialize()
  41742. /**
  41743. * Allows scaling the angle of the light for shadow generation only.
  41744. */
  41745. ], SpotLight.prototype, "shadowAngleScale", null);
  41746. __decorate([
  41747. BABYLON.serialize()
  41748. ], SpotLight.prototype, "exponent", void 0);
  41749. return SpotLight;
  41750. }(BABYLON.ShadowLight));
  41751. BABYLON.SpotLight = SpotLight;
  41752. })(BABYLON || (BABYLON = {}));
  41753. //# sourceMappingURL=babylon.spotLight.js.map
  41754. var BABYLON;
  41755. (function (BABYLON) {
  41756. var AnimationRange = /** @class */ (function () {
  41757. function AnimationRange(name, from, to) {
  41758. this.name = name;
  41759. this.from = from;
  41760. this.to = to;
  41761. }
  41762. AnimationRange.prototype.clone = function () {
  41763. return new AnimationRange(this.name, this.from, this.to);
  41764. };
  41765. return AnimationRange;
  41766. }());
  41767. BABYLON.AnimationRange = AnimationRange;
  41768. /**
  41769. * Composed of a frame, and an action function
  41770. */
  41771. var AnimationEvent = /** @class */ (function () {
  41772. function AnimationEvent(frame, action, onlyOnce) {
  41773. this.frame = frame;
  41774. this.action = action;
  41775. this.onlyOnce = onlyOnce;
  41776. this.isDone = false;
  41777. }
  41778. return AnimationEvent;
  41779. }());
  41780. BABYLON.AnimationEvent = AnimationEvent;
  41781. var PathCursor = /** @class */ (function () {
  41782. function PathCursor(path) {
  41783. this.path = path;
  41784. this._onchange = new Array();
  41785. this.value = 0;
  41786. this.animations = new Array();
  41787. }
  41788. PathCursor.prototype.getPoint = function () {
  41789. var point = this.path.getPointAtLengthPosition(this.value);
  41790. return new BABYLON.Vector3(point.x, 0, point.y);
  41791. };
  41792. PathCursor.prototype.moveAhead = function (step) {
  41793. if (step === void 0) { step = 0.002; }
  41794. this.move(step);
  41795. return this;
  41796. };
  41797. PathCursor.prototype.moveBack = function (step) {
  41798. if (step === void 0) { step = 0.002; }
  41799. this.move(-step);
  41800. return this;
  41801. };
  41802. PathCursor.prototype.move = function (step) {
  41803. if (Math.abs(step) > 1) {
  41804. throw "step size should be less than 1.";
  41805. }
  41806. this.value += step;
  41807. this.ensureLimits();
  41808. this.raiseOnChange();
  41809. return this;
  41810. };
  41811. PathCursor.prototype.ensureLimits = function () {
  41812. while (this.value > 1) {
  41813. this.value -= 1;
  41814. }
  41815. while (this.value < 0) {
  41816. this.value += 1;
  41817. }
  41818. return this;
  41819. };
  41820. // used by animation engine
  41821. PathCursor.prototype.raiseOnChange = function () {
  41822. var _this = this;
  41823. this._onchange.forEach(function (f) { return f(_this); });
  41824. return this;
  41825. };
  41826. PathCursor.prototype.onchange = function (f) {
  41827. this._onchange.push(f);
  41828. return this;
  41829. };
  41830. return PathCursor;
  41831. }());
  41832. BABYLON.PathCursor = PathCursor;
  41833. var AnimationKeyInterpolation;
  41834. (function (AnimationKeyInterpolation) {
  41835. /**
  41836. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  41837. */
  41838. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  41839. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  41840. var Animation = /** @class */ (function () {
  41841. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  41842. this.name = name;
  41843. this.targetProperty = targetProperty;
  41844. this.framePerSecond = framePerSecond;
  41845. this.dataType = dataType;
  41846. this.loopMode = loopMode;
  41847. this.enableBlending = enableBlending;
  41848. this._runtimeAnimations = new Array();
  41849. // The set of event that will be linked to this animation
  41850. this._events = new Array();
  41851. this.blendingSpeed = 0.01;
  41852. this._ranges = {};
  41853. this.targetPropertyPath = targetProperty.split(".");
  41854. this.dataType = dataType;
  41855. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  41856. }
  41857. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  41858. var dataType = undefined;
  41859. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  41860. dataType = Animation.ANIMATIONTYPE_FLOAT;
  41861. }
  41862. else if (from instanceof BABYLON.Quaternion) {
  41863. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  41864. }
  41865. else if (from instanceof BABYLON.Vector3) {
  41866. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  41867. }
  41868. else if (from instanceof BABYLON.Vector2) {
  41869. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  41870. }
  41871. else if (from instanceof BABYLON.Color3) {
  41872. dataType = Animation.ANIMATIONTYPE_COLOR3;
  41873. }
  41874. else if (from instanceof BABYLON.Size) {
  41875. dataType = Animation.ANIMATIONTYPE_SIZE;
  41876. }
  41877. if (dataType == undefined) {
  41878. return null;
  41879. }
  41880. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  41881. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  41882. animation.setKeys(keys);
  41883. if (easingFunction !== undefined) {
  41884. animation.setEasingFunction(easingFunction);
  41885. }
  41886. return animation;
  41887. };
  41888. /**
  41889. * Sets up an animation.
  41890. * @param property the property to animate
  41891. * @param animationType the animation type to apply
  41892. * @param easingFunction the easing function used in the animation
  41893. * @returns The created animation
  41894. */
  41895. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  41896. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  41897. animation.setEasingFunction(easingFunction);
  41898. return animation;
  41899. };
  41900. /**
  41901. * Create and start an animation on a node
  41902. * @param {string} name defines the name of the global animation that will be run on all nodes
  41903. * @param {BABYLON.Node} node defines the root node where the animation will take place
  41904. * @param {string} targetProperty defines property to animate
  41905. * @param {number} framePerSecond defines the number of frame per second yo use
  41906. * @param {number} totalFrame defines the number of frames in total
  41907. * @param {any} from defines the initial value
  41908. * @param {any} to defines the final value
  41909. * @param {number} loopMode defines which loop mode you want to use (off by default)
  41910. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  41911. * @param onAnimationEnd defines the callback to call when animation end
  41912. * @returns the animatable created for this animation
  41913. */
  41914. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41915. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41916. if (!animation) {
  41917. return null;
  41918. }
  41919. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41920. };
  41921. /**
  41922. * Create and start an animation on a node and its descendants
  41923. * @param {string} name defines the name of the global animation that will be run on all nodes
  41924. * @param {BABYLON.Node} node defines the root node where the animation will take place
  41925. * @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.
  41926. * @param {string} targetProperty defines property to animate
  41927. * @param {number} framePerSecond defines the number of frame per second yo use
  41928. * @param {number} totalFrame defines the number of frames in total
  41929. * @param {any} from defines the initial value
  41930. * @param {any} to defines the final value
  41931. * @param {number} loopMode defines which loop mode you want to use (off by default)
  41932. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  41933. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  41934. * @returns the list of animatables created for all nodes
  41935. * @example https://www.babylonjs-playground.com/#MH0VLI
  41936. */
  41937. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41938. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41939. if (!animation) {
  41940. return null;
  41941. }
  41942. var scene = node.getScene();
  41943. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41944. };
  41945. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41946. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41947. if (!animation) {
  41948. return null;
  41949. }
  41950. node.animations.push(animation);
  41951. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41952. };
  41953. /**
  41954. * Transition property of the Camera to the target Value.
  41955. * @param property The property to transition
  41956. * @param targetValue The target Value of the property
  41957. * @param host The object where the property to animate belongs
  41958. * @param scene Scene used to run the animation
  41959. * @param frameRate Framerate (in frame/s) to use
  41960. * @param transition The transition type we want to use
  41961. * @param duration The duration of the animation, in milliseconds
  41962. * @param onAnimationEnd Call back trigger at the end of the animation.
  41963. */
  41964. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  41965. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  41966. if (duration <= 0) {
  41967. host[property] = targetValue;
  41968. if (onAnimationEnd) {
  41969. onAnimationEnd();
  41970. }
  41971. return null;
  41972. }
  41973. var endFrame = frameRate * (duration / 1000);
  41974. transition.setKeys([{
  41975. frame: 0,
  41976. value: host[property].clone ? host[property].clone() : host[property]
  41977. },
  41978. {
  41979. frame: endFrame,
  41980. value: targetValue
  41981. }]);
  41982. if (!host.animations) {
  41983. host.animations = [];
  41984. }
  41985. host.animations.push(transition);
  41986. var animation = scene.beginAnimation(host, 0, endFrame, false);
  41987. animation.onAnimationEnd = onAnimationEnd;
  41988. return animation;
  41989. };
  41990. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  41991. /**
  41992. * Return the array of runtime animations currently using this animation
  41993. */
  41994. get: function () {
  41995. return this._runtimeAnimations;
  41996. },
  41997. enumerable: true,
  41998. configurable: true
  41999. });
  42000. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  42001. get: function () {
  42002. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  42003. var runtimeAnimation = _a[_i];
  42004. if (!runtimeAnimation.isStopped) {
  42005. return true;
  42006. }
  42007. }
  42008. return false;
  42009. },
  42010. enumerable: true,
  42011. configurable: true
  42012. });
  42013. // Methods
  42014. /**
  42015. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  42016. */
  42017. Animation.prototype.toString = function (fullDetails) {
  42018. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  42019. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  42020. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  42021. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  42022. if (fullDetails) {
  42023. ret += ", Ranges: {";
  42024. var first = true;
  42025. for (var name in this._ranges) {
  42026. if (first) {
  42027. ret += ", ";
  42028. first = false;
  42029. }
  42030. ret += name;
  42031. }
  42032. ret += "}";
  42033. }
  42034. return ret;
  42035. };
  42036. /**
  42037. * Add an event to this animation.
  42038. */
  42039. Animation.prototype.addEvent = function (event) {
  42040. this._events.push(event);
  42041. };
  42042. /**
  42043. * Remove all events found at the given frame
  42044. * @param frame
  42045. */
  42046. Animation.prototype.removeEvents = function (frame) {
  42047. for (var index = 0; index < this._events.length; index++) {
  42048. if (this._events[index].frame === frame) {
  42049. this._events.splice(index, 1);
  42050. index--;
  42051. }
  42052. }
  42053. };
  42054. Animation.prototype.getEvents = function () {
  42055. return this._events;
  42056. };
  42057. Animation.prototype.createRange = function (name, from, to) {
  42058. // check name not already in use; could happen for bones after serialized
  42059. if (!this._ranges[name]) {
  42060. this._ranges[name] = new AnimationRange(name, from, to);
  42061. }
  42062. };
  42063. Animation.prototype.deleteRange = function (name, deleteFrames) {
  42064. if (deleteFrames === void 0) { deleteFrames = true; }
  42065. var range = this._ranges[name];
  42066. if (!range) {
  42067. return;
  42068. }
  42069. if (deleteFrames) {
  42070. var from = range.from;
  42071. var to = range.to;
  42072. // this loop MUST go high to low for multiple splices to work
  42073. for (var key = this._keys.length - 1; key >= 0; key--) {
  42074. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  42075. this._keys.splice(key, 1);
  42076. }
  42077. }
  42078. }
  42079. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  42080. };
  42081. Animation.prototype.getRange = function (name) {
  42082. return this._ranges[name];
  42083. };
  42084. Animation.prototype.getKeys = function () {
  42085. return this._keys;
  42086. };
  42087. Animation.prototype.getHighestFrame = function () {
  42088. var ret = 0;
  42089. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  42090. if (ret < this._keys[key].frame) {
  42091. ret = this._keys[key].frame;
  42092. }
  42093. }
  42094. return ret;
  42095. };
  42096. Animation.prototype.getEasingFunction = function () {
  42097. return this._easingFunction;
  42098. };
  42099. Animation.prototype.setEasingFunction = function (easingFunction) {
  42100. this._easingFunction = easingFunction;
  42101. };
  42102. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  42103. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  42104. };
  42105. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42106. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42107. };
  42108. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  42109. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  42110. };
  42111. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42112. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  42113. };
  42114. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  42115. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  42116. };
  42117. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42118. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42119. };
  42120. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  42121. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  42122. };
  42123. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42124. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42125. };
  42126. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  42127. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  42128. };
  42129. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  42130. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  42131. };
  42132. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  42133. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  42134. };
  42135. Animation.prototype.clone = function () {
  42136. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  42137. clone.enableBlending = this.enableBlending;
  42138. clone.blendingSpeed = this.blendingSpeed;
  42139. if (this._keys) {
  42140. clone.setKeys(this._keys);
  42141. }
  42142. if (this._ranges) {
  42143. clone._ranges = {};
  42144. for (var name in this._ranges) {
  42145. var range = this._ranges[name];
  42146. if (!range) {
  42147. continue;
  42148. }
  42149. clone._ranges[name] = range.clone();
  42150. }
  42151. }
  42152. return clone;
  42153. };
  42154. Animation.prototype.setKeys = function (values) {
  42155. this._keys = values.slice(0);
  42156. };
  42157. Animation.prototype.serialize = function () {
  42158. var serializationObject = {};
  42159. serializationObject.name = this.name;
  42160. serializationObject.property = this.targetProperty;
  42161. serializationObject.framePerSecond = this.framePerSecond;
  42162. serializationObject.dataType = this.dataType;
  42163. serializationObject.loopBehavior = this.loopMode;
  42164. serializationObject.enableBlending = this.enableBlending;
  42165. serializationObject.blendingSpeed = this.blendingSpeed;
  42166. var dataType = this.dataType;
  42167. serializationObject.keys = [];
  42168. var keys = this.getKeys();
  42169. for (var index = 0; index < keys.length; index++) {
  42170. var animationKey = keys[index];
  42171. var key = {};
  42172. key.frame = animationKey.frame;
  42173. switch (dataType) {
  42174. case Animation.ANIMATIONTYPE_FLOAT:
  42175. key.values = [animationKey.value];
  42176. break;
  42177. case Animation.ANIMATIONTYPE_QUATERNION:
  42178. case Animation.ANIMATIONTYPE_MATRIX:
  42179. case Animation.ANIMATIONTYPE_VECTOR3:
  42180. case Animation.ANIMATIONTYPE_COLOR3:
  42181. key.values = animationKey.value.asArray();
  42182. break;
  42183. }
  42184. serializationObject.keys.push(key);
  42185. }
  42186. serializationObject.ranges = [];
  42187. for (var name in this._ranges) {
  42188. var source = this._ranges[name];
  42189. if (!source) {
  42190. continue;
  42191. }
  42192. var range = {};
  42193. range.name = name;
  42194. range.from = source.from;
  42195. range.to = source.to;
  42196. serializationObject.ranges.push(range);
  42197. }
  42198. return serializationObject;
  42199. };
  42200. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  42201. get: function () {
  42202. return Animation._ANIMATIONTYPE_FLOAT;
  42203. },
  42204. enumerable: true,
  42205. configurable: true
  42206. });
  42207. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  42208. get: function () {
  42209. return Animation._ANIMATIONTYPE_VECTOR3;
  42210. },
  42211. enumerable: true,
  42212. configurable: true
  42213. });
  42214. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  42215. get: function () {
  42216. return Animation._ANIMATIONTYPE_VECTOR2;
  42217. },
  42218. enumerable: true,
  42219. configurable: true
  42220. });
  42221. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  42222. get: function () {
  42223. return Animation._ANIMATIONTYPE_SIZE;
  42224. },
  42225. enumerable: true,
  42226. configurable: true
  42227. });
  42228. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  42229. get: function () {
  42230. return Animation._ANIMATIONTYPE_QUATERNION;
  42231. },
  42232. enumerable: true,
  42233. configurable: true
  42234. });
  42235. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  42236. get: function () {
  42237. return Animation._ANIMATIONTYPE_MATRIX;
  42238. },
  42239. enumerable: true,
  42240. configurable: true
  42241. });
  42242. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  42243. get: function () {
  42244. return Animation._ANIMATIONTYPE_COLOR3;
  42245. },
  42246. enumerable: true,
  42247. configurable: true
  42248. });
  42249. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  42250. get: function () {
  42251. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  42252. },
  42253. enumerable: true,
  42254. configurable: true
  42255. });
  42256. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  42257. get: function () {
  42258. return Animation._ANIMATIONLOOPMODE_CYCLE;
  42259. },
  42260. enumerable: true,
  42261. configurable: true
  42262. });
  42263. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  42264. get: function () {
  42265. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  42266. },
  42267. enumerable: true,
  42268. configurable: true
  42269. });
  42270. Animation.Parse = function (parsedAnimation) {
  42271. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  42272. var dataType = parsedAnimation.dataType;
  42273. var keys = [];
  42274. var data;
  42275. var index;
  42276. if (parsedAnimation.enableBlending) {
  42277. animation.enableBlending = parsedAnimation.enableBlending;
  42278. }
  42279. if (parsedAnimation.blendingSpeed) {
  42280. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  42281. }
  42282. for (index = 0; index < parsedAnimation.keys.length; index++) {
  42283. var key = parsedAnimation.keys[index];
  42284. var inTangent;
  42285. var outTangent;
  42286. switch (dataType) {
  42287. case Animation.ANIMATIONTYPE_FLOAT:
  42288. data = key.values[0];
  42289. if (key.values.length >= 1) {
  42290. inTangent = key.values[1];
  42291. }
  42292. if (key.values.length >= 2) {
  42293. outTangent = key.values[2];
  42294. }
  42295. break;
  42296. case Animation.ANIMATIONTYPE_QUATERNION:
  42297. data = BABYLON.Quaternion.FromArray(key.values);
  42298. if (key.values.length >= 8) {
  42299. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  42300. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  42301. inTangent = _inTangent;
  42302. }
  42303. }
  42304. if (key.values.length >= 12) {
  42305. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  42306. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  42307. outTangent = _outTangent;
  42308. }
  42309. }
  42310. break;
  42311. case Animation.ANIMATIONTYPE_MATRIX:
  42312. data = BABYLON.Matrix.FromArray(key.values);
  42313. break;
  42314. case Animation.ANIMATIONTYPE_COLOR3:
  42315. data = BABYLON.Color3.FromArray(key.values);
  42316. break;
  42317. case Animation.ANIMATIONTYPE_VECTOR3:
  42318. default:
  42319. data = BABYLON.Vector3.FromArray(key.values);
  42320. break;
  42321. }
  42322. var keyData = {};
  42323. keyData.frame = key.frame;
  42324. keyData.value = data;
  42325. if (inTangent != undefined) {
  42326. keyData.inTangent = inTangent;
  42327. }
  42328. if (outTangent != undefined) {
  42329. keyData.outTangent = outTangent;
  42330. }
  42331. keys.push(keyData);
  42332. }
  42333. animation.setKeys(keys);
  42334. if (parsedAnimation.ranges) {
  42335. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  42336. data = parsedAnimation.ranges[index];
  42337. animation.createRange(data.name, data.from, data.to);
  42338. }
  42339. }
  42340. return animation;
  42341. };
  42342. Animation.AppendSerializedAnimations = function (source, destination) {
  42343. if (source.animations) {
  42344. destination.animations = [];
  42345. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  42346. var animation = source.animations[animationIndex];
  42347. destination.animations.push(animation.serialize());
  42348. }
  42349. }
  42350. };
  42351. Animation.AllowMatricesInterpolation = false;
  42352. // Statics
  42353. Animation._ANIMATIONTYPE_FLOAT = 0;
  42354. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  42355. Animation._ANIMATIONTYPE_QUATERNION = 2;
  42356. Animation._ANIMATIONTYPE_MATRIX = 3;
  42357. Animation._ANIMATIONTYPE_COLOR3 = 4;
  42358. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  42359. Animation._ANIMATIONTYPE_SIZE = 6;
  42360. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  42361. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  42362. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  42363. return Animation;
  42364. }());
  42365. BABYLON.Animation = Animation;
  42366. })(BABYLON || (BABYLON = {}));
  42367. //# sourceMappingURL=babylon.animation.js.map
  42368. var BABYLON;
  42369. (function (BABYLON) {
  42370. /**
  42371. * This class defines the direct association between an animation and a target
  42372. */
  42373. var TargetedAnimation = /** @class */ (function () {
  42374. function TargetedAnimation() {
  42375. }
  42376. return TargetedAnimation;
  42377. }());
  42378. BABYLON.TargetedAnimation = TargetedAnimation;
  42379. /**
  42380. * Use this class to create coordinated animations on multiple targets
  42381. */
  42382. var AnimationGroup = /** @class */ (function () {
  42383. function AnimationGroup(name, scene) {
  42384. if (scene === void 0) { scene = null; }
  42385. this.name = name;
  42386. this._targetedAnimations = new Array();
  42387. this._animatables = new Array();
  42388. this._from = Number.MAX_VALUE;
  42389. this._to = Number.MIN_VALUE;
  42390. this._speedRatio = 1;
  42391. this.onAnimationEndObservable = new BABYLON.Observable();
  42392. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  42393. this._scene.animationGroups.push(this);
  42394. }
  42395. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  42396. /**
  42397. * Define if the animations are started
  42398. */
  42399. get: function () {
  42400. return this._isStarted;
  42401. },
  42402. enumerable: true,
  42403. configurable: true
  42404. });
  42405. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  42406. /**
  42407. * Gets or sets the speed ratio to use for all animations
  42408. */
  42409. get: function () {
  42410. return this._speedRatio;
  42411. },
  42412. /**
  42413. * Gets or sets the speed ratio to use for all animations
  42414. */
  42415. set: function (value) {
  42416. if (this._speedRatio === value) {
  42417. return;
  42418. }
  42419. this._speedRatio = value;
  42420. for (var index = 0; index < this._animatables.length; index++) {
  42421. var animatable = this._animatables[index];
  42422. animatable.speedRatio = this._speedRatio;
  42423. }
  42424. },
  42425. enumerable: true,
  42426. configurable: true
  42427. });
  42428. /**
  42429. * Add an animation (with its target) in the group
  42430. * @param animation defines the animation we want to add
  42431. * @param target defines the target of the animation
  42432. * @returns the {BABYLON.TargetedAnimation} object
  42433. */
  42434. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  42435. var targetedAnimation = {
  42436. animation: animation,
  42437. target: target
  42438. };
  42439. var keys = animation.getKeys();
  42440. if (this._from > keys[0].frame) {
  42441. this._from = keys[0].frame;
  42442. }
  42443. if (this._to < keys[keys.length - 1].frame) {
  42444. this._to = keys[keys.length - 1].frame;
  42445. }
  42446. this._targetedAnimations.push(targetedAnimation);
  42447. return targetedAnimation;
  42448. };
  42449. /**
  42450. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  42451. * It can add constant keys at begin or end
  42452. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smaller begin frame of all animations
  42453. * @param endFrame defines the new end frame for all animations. It can't be smaller than the larger end frame of all animations
  42454. */
  42455. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  42456. beginFrame = Math.min(beginFrame, this._from);
  42457. endFrame = Math.min(endFrame, this._to);
  42458. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42459. var targetedAnimation = this._targetedAnimations[index];
  42460. var keys = targetedAnimation.animation.getKeys();
  42461. var startKey = keys[0];
  42462. var endKey = keys[keys.length - 1];
  42463. if (startKey.frame > beginFrame) {
  42464. var newKey = {
  42465. frame: beginFrame,
  42466. value: startKey.value,
  42467. inTangent: startKey.inTangent,
  42468. outTangent: startKey.outTangent
  42469. };
  42470. keys.splice(0, 0, newKey);
  42471. }
  42472. if (endKey.frame < endFrame) {
  42473. var newKey = {
  42474. frame: endFrame,
  42475. value: endKey.value,
  42476. inTangent: startKey.outTangent,
  42477. outTangent: startKey.outTangent
  42478. };
  42479. keys.push(newKey);
  42480. }
  42481. }
  42482. return this;
  42483. };
  42484. /**
  42485. * Start all animations on given targets
  42486. * @param loop defines if animations must loop
  42487. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  42488. */
  42489. AnimationGroup.prototype.start = function (loop, speedRatio) {
  42490. var _this = this;
  42491. if (loop === void 0) { loop = false; }
  42492. if (speedRatio === void 0) { speedRatio = 1; }
  42493. if (this._isStarted || this._targetedAnimations.length === 0) {
  42494. return this;
  42495. }
  42496. var _loop_1 = function () {
  42497. var targetedAnimation = this_1._targetedAnimations[index];
  42498. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  42499. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  42500. }));
  42501. };
  42502. var this_1 = this;
  42503. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42504. _loop_1();
  42505. }
  42506. this._speedRatio = speedRatio;
  42507. this._isStarted = true;
  42508. return this;
  42509. };
  42510. /**
  42511. * Pause all animations
  42512. */
  42513. AnimationGroup.prototype.pause = function () {
  42514. if (!this._isStarted) {
  42515. return this;
  42516. }
  42517. for (var index = 0; index < this._animatables.length; index++) {
  42518. var animatable = this._animatables[index];
  42519. animatable.pause();
  42520. }
  42521. return this;
  42522. };
  42523. /**
  42524. * Play all animations to initial state
  42525. * This function will start() the animations if they were not started or will restart() them if they were paused
  42526. * @param loop defines if animations must loop
  42527. */
  42528. AnimationGroup.prototype.play = function (loop) {
  42529. if (this.isStarted) {
  42530. if (loop !== undefined) {
  42531. for (var index = 0; index < this._animatables.length; index++) {
  42532. var animatable = this._animatables[index];
  42533. animatable.loopAnimation = loop;
  42534. }
  42535. }
  42536. this.restart();
  42537. }
  42538. else {
  42539. this.start(loop, this._speedRatio);
  42540. }
  42541. return this;
  42542. };
  42543. /**
  42544. * Reset all animations to initial state
  42545. */
  42546. AnimationGroup.prototype.reset = function () {
  42547. if (!this._isStarted) {
  42548. return this;
  42549. }
  42550. for (var index = 0; index < this._animatables.length; index++) {
  42551. var animatable = this._animatables[index];
  42552. animatable.reset();
  42553. }
  42554. return this;
  42555. };
  42556. /**
  42557. * Restart animations from key 0
  42558. */
  42559. AnimationGroup.prototype.restart = function () {
  42560. if (!this._isStarted) {
  42561. return this;
  42562. }
  42563. for (var index = 0; index < this._animatables.length; index++) {
  42564. var animatable = this._animatables[index];
  42565. animatable.restart();
  42566. }
  42567. return this;
  42568. };
  42569. /**
  42570. * Stop all animations
  42571. */
  42572. AnimationGroup.prototype.stop = function () {
  42573. if (!this._isStarted) {
  42574. return this;
  42575. }
  42576. for (var index = 0; index < this._animatables.length; index++) {
  42577. var animatable = this._animatables[index];
  42578. animatable.stop();
  42579. }
  42580. this._isStarted = false;
  42581. return this;
  42582. };
  42583. /**
  42584. * Dispose all associated resources
  42585. */
  42586. AnimationGroup.prototype.dispose = function () {
  42587. this._targetedAnimations = [];
  42588. this._animatables = [];
  42589. var index = this._scene.animationGroups.indexOf(this);
  42590. if (index > -1) {
  42591. this._scene.animationGroups.splice(index, 1);
  42592. }
  42593. };
  42594. return AnimationGroup;
  42595. }());
  42596. BABYLON.AnimationGroup = AnimationGroup;
  42597. })(BABYLON || (BABYLON = {}));
  42598. //# sourceMappingURL=babylon.animationGroup.js.map
  42599. var BABYLON;
  42600. (function (BABYLON) {
  42601. var RuntimeAnimation = /** @class */ (function () {
  42602. function RuntimeAnimation(target, animation) {
  42603. this._offsetsCache = {};
  42604. this._highLimitsCache = {};
  42605. this._stopped = false;
  42606. this._blendingFactor = 0;
  42607. this._ratioOffset = 0;
  42608. this._animation = animation;
  42609. this._target = target;
  42610. animation._runtimeAnimations.push(this);
  42611. }
  42612. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  42613. get: function () {
  42614. return this._animation;
  42615. },
  42616. enumerable: true,
  42617. configurable: true
  42618. });
  42619. RuntimeAnimation.prototype.reset = function () {
  42620. this._offsetsCache = {};
  42621. this._highLimitsCache = {};
  42622. this.currentFrame = 0;
  42623. this._blendingFactor = 0;
  42624. this._originalBlendValue = null;
  42625. };
  42626. RuntimeAnimation.prototype.isStopped = function () {
  42627. return this._stopped;
  42628. };
  42629. RuntimeAnimation.prototype.dispose = function () {
  42630. var index = this._animation.runtimeAnimations.indexOf(this);
  42631. if (index > -1) {
  42632. this._animation.runtimeAnimations.splice(index, 1);
  42633. }
  42634. };
  42635. RuntimeAnimation.prototype._getKeyValue = function (value) {
  42636. if (typeof value === "function") {
  42637. return value();
  42638. }
  42639. return value;
  42640. };
  42641. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  42642. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  42643. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  42644. }
  42645. this.currentFrame = currentFrame;
  42646. var keys = this._animation.getKeys();
  42647. // Try to get a hash to find the right key
  42648. 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));
  42649. if (keys[startKeyIndex].frame >= currentFrame) {
  42650. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  42651. startKeyIndex--;
  42652. }
  42653. }
  42654. for (var key = startKeyIndex; key < keys.length; key++) {
  42655. var endKey = keys[key + 1];
  42656. if (endKey.frame >= currentFrame) {
  42657. var startKey = keys[key];
  42658. var startValue = this._getKeyValue(startKey.value);
  42659. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  42660. return startValue;
  42661. }
  42662. var endValue = this._getKeyValue(endKey.value);
  42663. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  42664. var frameDelta = endKey.frame - startKey.frame;
  42665. // gradient : percent of currentFrame between the frame inf and the frame sup
  42666. var gradient = (currentFrame - startKey.frame) / frameDelta;
  42667. // check for easingFunction and correction of gradient
  42668. var easingFunction = this._animation.getEasingFunction();
  42669. if (easingFunction != null) {
  42670. gradient = easingFunction.ease(gradient);
  42671. }
  42672. switch (this._animation.dataType) {
  42673. // Float
  42674. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42675. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  42676. switch (loopMode) {
  42677. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42678. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42679. return floatValue;
  42680. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42681. return offsetValue * repeatCount + floatValue;
  42682. }
  42683. break;
  42684. // Quaternion
  42685. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42686. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  42687. switch (loopMode) {
  42688. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42689. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42690. return quatValue;
  42691. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42692. return quatValue.add(offsetValue.scale(repeatCount));
  42693. }
  42694. return quatValue;
  42695. // Vector3
  42696. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42697. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  42698. switch (loopMode) {
  42699. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42700. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42701. return vec3Value;
  42702. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42703. return vec3Value.add(offsetValue.scale(repeatCount));
  42704. }
  42705. // Vector2
  42706. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42707. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  42708. switch (loopMode) {
  42709. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42710. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42711. return vec2Value;
  42712. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42713. return vec2Value.add(offsetValue.scale(repeatCount));
  42714. }
  42715. // Size
  42716. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42717. switch (loopMode) {
  42718. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42719. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42720. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  42721. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42722. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42723. }
  42724. // Color3
  42725. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42726. switch (loopMode) {
  42727. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42728. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42729. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  42730. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42731. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42732. }
  42733. // Matrix
  42734. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  42735. switch (loopMode) {
  42736. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42737. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42738. if (BABYLON.Animation.AllowMatricesInterpolation) {
  42739. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  42740. }
  42741. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42742. return startValue;
  42743. }
  42744. default:
  42745. break;
  42746. }
  42747. break;
  42748. }
  42749. }
  42750. return this._getKeyValue(keys[keys.length - 1].value);
  42751. };
  42752. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  42753. if (blend === void 0) { blend = false; }
  42754. // Set value
  42755. var path;
  42756. var destination;
  42757. var targetPropertyPath = this._animation.targetPropertyPath;
  42758. if (targetPropertyPath.length > 1) {
  42759. var property = this._target[targetPropertyPath[0]];
  42760. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  42761. property = property[targetPropertyPath[index]];
  42762. }
  42763. path = targetPropertyPath[targetPropertyPath.length - 1];
  42764. destination = property;
  42765. }
  42766. else {
  42767. path = targetPropertyPath[0];
  42768. destination = this._target;
  42769. }
  42770. // Blending
  42771. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  42772. if (!this._originalBlendValue) {
  42773. if (destination[path].clone) {
  42774. this._originalBlendValue = destination[path].clone();
  42775. }
  42776. else {
  42777. this._originalBlendValue = destination[path];
  42778. }
  42779. }
  42780. if (this._originalBlendValue.prototype) {
  42781. if (this._originalBlendValue.prototype.Lerp) {
  42782. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  42783. }
  42784. else {
  42785. destination[path] = currentValue;
  42786. }
  42787. }
  42788. else if (this._originalBlendValue.m) {
  42789. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  42790. }
  42791. else {
  42792. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  42793. }
  42794. this._blendingFactor += this._animation.blendingSpeed;
  42795. }
  42796. else {
  42797. destination[path] = currentValue;
  42798. }
  42799. if (this._target.markAsDirty) {
  42800. this._target.markAsDirty(this._animation.targetProperty);
  42801. }
  42802. };
  42803. RuntimeAnimation.prototype.goToFrame = function (frame) {
  42804. var keys = this._animation.getKeys();
  42805. if (frame < keys[0].frame) {
  42806. frame = keys[0].frame;
  42807. }
  42808. else if (frame > keys[keys.length - 1].frame) {
  42809. frame = keys[keys.length - 1].frame;
  42810. }
  42811. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  42812. this.setValue(currentValue);
  42813. };
  42814. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  42815. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  42816. this._ratioOffset = this._previousRatio - newRatio;
  42817. };
  42818. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  42819. if (blend === void 0) { blend = false; }
  42820. var targetPropertyPath = this._animation.targetPropertyPath;
  42821. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  42822. this._stopped = true;
  42823. return false;
  42824. }
  42825. var returnValue = true;
  42826. var keys = this._animation.getKeys();
  42827. // Adding a start key at frame 0 if missing
  42828. if (keys[0].frame !== 0) {
  42829. var newKey = { frame: 0, value: keys[0].value };
  42830. keys.splice(0, 0, newKey);
  42831. }
  42832. // Check limits
  42833. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  42834. from = keys[0].frame;
  42835. }
  42836. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  42837. to = keys[keys.length - 1].frame;
  42838. }
  42839. //to and from cannot be the same key
  42840. if (from === to) {
  42841. if (from > keys[0].frame) {
  42842. from--;
  42843. }
  42844. else if (to < keys[keys.length - 1].frame) {
  42845. to++;
  42846. }
  42847. }
  42848. // Compute ratio
  42849. var range = to - from;
  42850. var offsetValue;
  42851. // ratio represents the frame delta between from and to
  42852. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  42853. var highLimitValue = 0;
  42854. this._previousDelay = delay;
  42855. this._previousRatio = ratio;
  42856. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  42857. returnValue = false;
  42858. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  42859. }
  42860. else {
  42861. // Get max value if required
  42862. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  42863. var keyOffset = to.toString() + from.toString();
  42864. if (!this._offsetsCache[keyOffset]) {
  42865. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42866. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42867. switch (this._animation.dataType) {
  42868. // Float
  42869. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42870. this._offsetsCache[keyOffset] = toValue - fromValue;
  42871. break;
  42872. // Quaternion
  42873. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42874. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42875. break;
  42876. // Vector3
  42877. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42878. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42879. // Vector2
  42880. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42881. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42882. // Size
  42883. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42884. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42885. // Color3
  42886. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42887. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42888. default:
  42889. break;
  42890. }
  42891. this._highLimitsCache[keyOffset] = toValue;
  42892. }
  42893. highLimitValue = this._highLimitsCache[keyOffset];
  42894. offsetValue = this._offsetsCache[keyOffset];
  42895. }
  42896. }
  42897. if (offsetValue === undefined) {
  42898. switch (this._animation.dataType) {
  42899. // Float
  42900. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42901. offsetValue = 0;
  42902. break;
  42903. // Quaternion
  42904. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42905. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  42906. break;
  42907. // Vector3
  42908. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42909. offsetValue = BABYLON.Vector3.Zero();
  42910. break;
  42911. // Vector2
  42912. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42913. offsetValue = BABYLON.Vector2.Zero();
  42914. break;
  42915. // Size
  42916. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42917. offsetValue = BABYLON.Size.Zero();
  42918. break;
  42919. // Color3
  42920. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42921. offsetValue = BABYLON.Color3.Black();
  42922. }
  42923. }
  42924. // Compute value
  42925. var repeatCount = (ratio / range) >> 0;
  42926. var currentFrame = returnValue ? from + ratio % range : to;
  42927. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  42928. // Set value
  42929. this.setValue(currentValue);
  42930. // Check events
  42931. var events = this._animation.getEvents();
  42932. for (var index = 0; index < events.length; index++) {
  42933. // Make sure current frame has passed event frame and that event frame is within the current range
  42934. // Also, handle both forward and reverse animations
  42935. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  42936. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  42937. var event = events[index];
  42938. if (!event.isDone) {
  42939. // If event should be done only once, remove it.
  42940. if (event.onlyOnce) {
  42941. events.splice(index, 1);
  42942. index--;
  42943. }
  42944. event.isDone = true;
  42945. event.action();
  42946. } // Don't do anything if the event has already be done.
  42947. }
  42948. else if (events[index].isDone && !events[index].onlyOnce) {
  42949. // reset event, the animation is looping
  42950. events[index].isDone = false;
  42951. }
  42952. }
  42953. if (!returnValue) {
  42954. this._stopped = true;
  42955. }
  42956. return returnValue;
  42957. };
  42958. return RuntimeAnimation;
  42959. }());
  42960. BABYLON.RuntimeAnimation = RuntimeAnimation;
  42961. })(BABYLON || (BABYLON = {}));
  42962. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  42963. var BABYLON;
  42964. (function (BABYLON) {
  42965. var Animatable = /** @class */ (function () {
  42966. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  42967. if (fromFrame === void 0) { fromFrame = 0; }
  42968. if (toFrame === void 0) { toFrame = 100; }
  42969. if (loopAnimation === void 0) { loopAnimation = false; }
  42970. if (speedRatio === void 0) { speedRatio = 1.0; }
  42971. this.target = target;
  42972. this.fromFrame = fromFrame;
  42973. this.toFrame = toFrame;
  42974. this.loopAnimation = loopAnimation;
  42975. this.onAnimationEnd = onAnimationEnd;
  42976. this._localDelayOffset = null;
  42977. this._pausedDelay = null;
  42978. this._runtimeAnimations = new Array();
  42979. this._paused = false;
  42980. this._speedRatio = 1;
  42981. this.animationStarted = false;
  42982. if (animations) {
  42983. this.appendAnimations(target, animations);
  42984. }
  42985. this._speedRatio = speedRatio;
  42986. this._scene = scene;
  42987. scene._activeAnimatables.push(this);
  42988. }
  42989. Object.defineProperty(Animatable.prototype, "speedRatio", {
  42990. get: function () {
  42991. return this._speedRatio;
  42992. },
  42993. set: function (value) {
  42994. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  42995. var animation = this._runtimeAnimations[index];
  42996. animation._prepareForSpeedRatioChange(value);
  42997. }
  42998. this._speedRatio = value;
  42999. },
  43000. enumerable: true,
  43001. configurable: true
  43002. });
  43003. // Methods
  43004. Animatable.prototype.getAnimations = function () {
  43005. return this._runtimeAnimations;
  43006. };
  43007. Animatable.prototype.appendAnimations = function (target, animations) {
  43008. for (var index = 0; index < animations.length; index++) {
  43009. var animation = animations[index];
  43010. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  43011. }
  43012. };
  43013. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  43014. var runtimeAnimations = this._runtimeAnimations;
  43015. for (var index = 0; index < runtimeAnimations.length; index++) {
  43016. if (runtimeAnimations[index].animation.targetProperty === property) {
  43017. return runtimeAnimations[index].animation;
  43018. }
  43019. }
  43020. return null;
  43021. };
  43022. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  43023. var runtimeAnimations = this._runtimeAnimations;
  43024. for (var index = 0; index < runtimeAnimations.length; index++) {
  43025. if (runtimeAnimations[index].animation.targetProperty === property) {
  43026. return runtimeAnimations[index];
  43027. }
  43028. }
  43029. return null;
  43030. };
  43031. Animatable.prototype.reset = function () {
  43032. var runtimeAnimations = this._runtimeAnimations;
  43033. for (var index = 0; index < runtimeAnimations.length; index++) {
  43034. runtimeAnimations[index].reset();
  43035. }
  43036. // Reset to original value
  43037. for (index = 0; index < runtimeAnimations.length; index++) {
  43038. var animation = runtimeAnimations[index];
  43039. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  43040. }
  43041. this._localDelayOffset = null;
  43042. this._pausedDelay = null;
  43043. };
  43044. Animatable.prototype.enableBlending = function (blendingSpeed) {
  43045. var runtimeAnimations = this._runtimeAnimations;
  43046. for (var index = 0; index < runtimeAnimations.length; index++) {
  43047. runtimeAnimations[index].animation.enableBlending = true;
  43048. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  43049. }
  43050. };
  43051. Animatable.prototype.disableBlending = function () {
  43052. var runtimeAnimations = this._runtimeAnimations;
  43053. for (var index = 0; index < runtimeAnimations.length; index++) {
  43054. runtimeAnimations[index].animation.enableBlending = false;
  43055. }
  43056. };
  43057. Animatable.prototype.goToFrame = function (frame) {
  43058. var runtimeAnimations = this._runtimeAnimations;
  43059. if (runtimeAnimations[0]) {
  43060. var fps = runtimeAnimations[0].animation.framePerSecond;
  43061. var currentFrame = runtimeAnimations[0].currentFrame;
  43062. var adjustTime = frame - currentFrame;
  43063. var delay = adjustTime * 1000 / fps;
  43064. if (this._localDelayOffset === null) {
  43065. this._localDelayOffset = 0;
  43066. }
  43067. this._localDelayOffset -= delay;
  43068. }
  43069. for (var index = 0; index < runtimeAnimations.length; index++) {
  43070. runtimeAnimations[index].goToFrame(frame);
  43071. }
  43072. };
  43073. Animatable.prototype.pause = function () {
  43074. if (this._paused) {
  43075. return;
  43076. }
  43077. this._paused = true;
  43078. };
  43079. Animatable.prototype.restart = function () {
  43080. this._paused = false;
  43081. };
  43082. Animatable.prototype.stop = function (animationName) {
  43083. if (animationName) {
  43084. var idx = this._scene._activeAnimatables.indexOf(this);
  43085. if (idx > -1) {
  43086. var runtimeAnimations = this._runtimeAnimations;
  43087. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  43088. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  43089. continue;
  43090. }
  43091. runtimeAnimations[index].dispose();
  43092. runtimeAnimations.splice(index, 1);
  43093. }
  43094. if (runtimeAnimations.length == 0) {
  43095. this._scene._activeAnimatables.splice(idx, 1);
  43096. if (this.onAnimationEnd) {
  43097. this.onAnimationEnd();
  43098. }
  43099. }
  43100. }
  43101. }
  43102. else {
  43103. var index = this._scene._activeAnimatables.indexOf(this);
  43104. if (index > -1) {
  43105. this._scene._activeAnimatables.splice(index, 1);
  43106. var runtimeAnimations = this._runtimeAnimations;
  43107. for (var index = 0; index < runtimeAnimations.length; index++) {
  43108. runtimeAnimations[index].dispose();
  43109. }
  43110. if (this.onAnimationEnd) {
  43111. this.onAnimationEnd();
  43112. }
  43113. }
  43114. }
  43115. };
  43116. Animatable.prototype._animate = function (delay) {
  43117. if (this._paused) {
  43118. this.animationStarted = false;
  43119. if (this._pausedDelay === null) {
  43120. this._pausedDelay = delay;
  43121. }
  43122. return true;
  43123. }
  43124. if (this._localDelayOffset === null) {
  43125. this._localDelayOffset = delay;
  43126. }
  43127. else if (this._pausedDelay !== null) {
  43128. this._localDelayOffset += delay - this._pausedDelay;
  43129. this._pausedDelay = null;
  43130. }
  43131. // Animating
  43132. var running = false;
  43133. var runtimeAnimations = this._runtimeAnimations;
  43134. var index;
  43135. for (index = 0; index < runtimeAnimations.length; index++) {
  43136. var animation = runtimeAnimations[index];
  43137. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  43138. running = running || isRunning;
  43139. }
  43140. this.animationStarted = running;
  43141. if (!running) {
  43142. // Remove from active animatables
  43143. index = this._scene._activeAnimatables.indexOf(this);
  43144. this._scene._activeAnimatables.splice(index, 1);
  43145. // Dispose all runtime animations
  43146. for (index = 0; index < runtimeAnimations.length; index++) {
  43147. runtimeAnimations[index].dispose();
  43148. }
  43149. }
  43150. if (!running && this.onAnimationEnd) {
  43151. this.onAnimationEnd();
  43152. this.onAnimationEnd = null;
  43153. }
  43154. return running;
  43155. };
  43156. return Animatable;
  43157. }());
  43158. BABYLON.Animatable = Animatable;
  43159. })(BABYLON || (BABYLON = {}));
  43160. //# sourceMappingURL=babylon.animatable.js.map
  43161. var BABYLON;
  43162. (function (BABYLON) {
  43163. var EasingFunction = /** @class */ (function () {
  43164. function EasingFunction() {
  43165. // Properties
  43166. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  43167. }
  43168. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  43169. get: function () {
  43170. return EasingFunction._EASINGMODE_EASEIN;
  43171. },
  43172. enumerable: true,
  43173. configurable: true
  43174. });
  43175. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  43176. get: function () {
  43177. return EasingFunction._EASINGMODE_EASEOUT;
  43178. },
  43179. enumerable: true,
  43180. configurable: true
  43181. });
  43182. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  43183. get: function () {
  43184. return EasingFunction._EASINGMODE_EASEINOUT;
  43185. },
  43186. enumerable: true,
  43187. configurable: true
  43188. });
  43189. EasingFunction.prototype.setEasingMode = function (easingMode) {
  43190. var n = Math.min(Math.max(easingMode, 0), 2);
  43191. this._easingMode = n;
  43192. };
  43193. EasingFunction.prototype.getEasingMode = function () {
  43194. return this._easingMode;
  43195. };
  43196. EasingFunction.prototype.easeInCore = function (gradient) {
  43197. throw new Error('You must implement this method');
  43198. };
  43199. EasingFunction.prototype.ease = function (gradient) {
  43200. switch (this._easingMode) {
  43201. case EasingFunction.EASINGMODE_EASEIN:
  43202. return this.easeInCore(gradient);
  43203. case EasingFunction.EASINGMODE_EASEOUT:
  43204. return (1 - this.easeInCore(1 - gradient));
  43205. }
  43206. if (gradient >= 0.5) {
  43207. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  43208. }
  43209. return (this.easeInCore(gradient * 2) * 0.5);
  43210. };
  43211. //Statics
  43212. EasingFunction._EASINGMODE_EASEIN = 0;
  43213. EasingFunction._EASINGMODE_EASEOUT = 1;
  43214. EasingFunction._EASINGMODE_EASEINOUT = 2;
  43215. return EasingFunction;
  43216. }());
  43217. BABYLON.EasingFunction = EasingFunction;
  43218. var CircleEase = /** @class */ (function (_super) {
  43219. __extends(CircleEase, _super);
  43220. function CircleEase() {
  43221. return _super !== null && _super.apply(this, arguments) || this;
  43222. }
  43223. CircleEase.prototype.easeInCore = function (gradient) {
  43224. gradient = Math.max(0, Math.min(1, gradient));
  43225. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  43226. };
  43227. return CircleEase;
  43228. }(EasingFunction));
  43229. BABYLON.CircleEase = CircleEase;
  43230. var BackEase = /** @class */ (function (_super) {
  43231. __extends(BackEase, _super);
  43232. function BackEase(amplitude) {
  43233. if (amplitude === void 0) { amplitude = 1; }
  43234. var _this = _super.call(this) || this;
  43235. _this.amplitude = amplitude;
  43236. return _this;
  43237. }
  43238. BackEase.prototype.easeInCore = function (gradient) {
  43239. var num = Math.max(0, this.amplitude);
  43240. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  43241. };
  43242. return BackEase;
  43243. }(EasingFunction));
  43244. BABYLON.BackEase = BackEase;
  43245. var BounceEase = /** @class */ (function (_super) {
  43246. __extends(BounceEase, _super);
  43247. function BounceEase(bounces, bounciness) {
  43248. if (bounces === void 0) { bounces = 3; }
  43249. if (bounciness === void 0) { bounciness = 2; }
  43250. var _this = _super.call(this) || this;
  43251. _this.bounces = bounces;
  43252. _this.bounciness = bounciness;
  43253. return _this;
  43254. }
  43255. BounceEase.prototype.easeInCore = function (gradient) {
  43256. var y = Math.max(0.0, this.bounces);
  43257. var bounciness = this.bounciness;
  43258. if (bounciness <= 1.0) {
  43259. bounciness = 1.001;
  43260. }
  43261. var num9 = Math.pow(bounciness, y);
  43262. var num5 = 1.0 - bounciness;
  43263. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  43264. var num15 = gradient * num4;
  43265. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  43266. var num3 = Math.floor(num65);
  43267. var num13 = num3 + 1.0;
  43268. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  43269. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  43270. var num7 = (num8 + num12) * 0.5;
  43271. var num6 = gradient - num7;
  43272. var num2 = num7 - num8;
  43273. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  43274. };
  43275. return BounceEase;
  43276. }(EasingFunction));
  43277. BABYLON.BounceEase = BounceEase;
  43278. var CubicEase = /** @class */ (function (_super) {
  43279. __extends(CubicEase, _super);
  43280. function CubicEase() {
  43281. return _super !== null && _super.apply(this, arguments) || this;
  43282. }
  43283. CubicEase.prototype.easeInCore = function (gradient) {
  43284. return (gradient * gradient * gradient);
  43285. };
  43286. return CubicEase;
  43287. }(EasingFunction));
  43288. BABYLON.CubicEase = CubicEase;
  43289. var ElasticEase = /** @class */ (function (_super) {
  43290. __extends(ElasticEase, _super);
  43291. function ElasticEase(oscillations, springiness) {
  43292. if (oscillations === void 0) { oscillations = 3; }
  43293. if (springiness === void 0) { springiness = 3; }
  43294. var _this = _super.call(this) || this;
  43295. _this.oscillations = oscillations;
  43296. _this.springiness = springiness;
  43297. return _this;
  43298. }
  43299. ElasticEase.prototype.easeInCore = function (gradient) {
  43300. var num2;
  43301. var num3 = Math.max(0.0, this.oscillations);
  43302. var num = Math.max(0.0, this.springiness);
  43303. if (num == 0) {
  43304. num2 = gradient;
  43305. }
  43306. else {
  43307. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  43308. }
  43309. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  43310. };
  43311. return ElasticEase;
  43312. }(EasingFunction));
  43313. BABYLON.ElasticEase = ElasticEase;
  43314. var ExponentialEase = /** @class */ (function (_super) {
  43315. __extends(ExponentialEase, _super);
  43316. function ExponentialEase(exponent) {
  43317. if (exponent === void 0) { exponent = 2; }
  43318. var _this = _super.call(this) || this;
  43319. _this.exponent = exponent;
  43320. return _this;
  43321. }
  43322. ExponentialEase.prototype.easeInCore = function (gradient) {
  43323. if (this.exponent <= 0) {
  43324. return gradient;
  43325. }
  43326. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  43327. };
  43328. return ExponentialEase;
  43329. }(EasingFunction));
  43330. BABYLON.ExponentialEase = ExponentialEase;
  43331. var PowerEase = /** @class */ (function (_super) {
  43332. __extends(PowerEase, _super);
  43333. function PowerEase(power) {
  43334. if (power === void 0) { power = 2; }
  43335. var _this = _super.call(this) || this;
  43336. _this.power = power;
  43337. return _this;
  43338. }
  43339. PowerEase.prototype.easeInCore = function (gradient) {
  43340. var y = Math.max(0.0, this.power);
  43341. return Math.pow(gradient, y);
  43342. };
  43343. return PowerEase;
  43344. }(EasingFunction));
  43345. BABYLON.PowerEase = PowerEase;
  43346. var QuadraticEase = /** @class */ (function (_super) {
  43347. __extends(QuadraticEase, _super);
  43348. function QuadraticEase() {
  43349. return _super !== null && _super.apply(this, arguments) || this;
  43350. }
  43351. QuadraticEase.prototype.easeInCore = function (gradient) {
  43352. return (gradient * gradient);
  43353. };
  43354. return QuadraticEase;
  43355. }(EasingFunction));
  43356. BABYLON.QuadraticEase = QuadraticEase;
  43357. var QuarticEase = /** @class */ (function (_super) {
  43358. __extends(QuarticEase, _super);
  43359. function QuarticEase() {
  43360. return _super !== null && _super.apply(this, arguments) || this;
  43361. }
  43362. QuarticEase.prototype.easeInCore = function (gradient) {
  43363. return (gradient * gradient * gradient * gradient);
  43364. };
  43365. return QuarticEase;
  43366. }(EasingFunction));
  43367. BABYLON.QuarticEase = QuarticEase;
  43368. var QuinticEase = /** @class */ (function (_super) {
  43369. __extends(QuinticEase, _super);
  43370. function QuinticEase() {
  43371. return _super !== null && _super.apply(this, arguments) || this;
  43372. }
  43373. QuinticEase.prototype.easeInCore = function (gradient) {
  43374. return (gradient * gradient * gradient * gradient * gradient);
  43375. };
  43376. return QuinticEase;
  43377. }(EasingFunction));
  43378. BABYLON.QuinticEase = QuinticEase;
  43379. var SineEase = /** @class */ (function (_super) {
  43380. __extends(SineEase, _super);
  43381. function SineEase() {
  43382. return _super !== null && _super.apply(this, arguments) || this;
  43383. }
  43384. SineEase.prototype.easeInCore = function (gradient) {
  43385. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  43386. };
  43387. return SineEase;
  43388. }(EasingFunction));
  43389. BABYLON.SineEase = SineEase;
  43390. var BezierCurveEase = /** @class */ (function (_super) {
  43391. __extends(BezierCurveEase, _super);
  43392. function BezierCurveEase(x1, y1, x2, y2) {
  43393. if (x1 === void 0) { x1 = 0; }
  43394. if (y1 === void 0) { y1 = 0; }
  43395. if (x2 === void 0) { x2 = 1; }
  43396. if (y2 === void 0) { y2 = 1; }
  43397. var _this = _super.call(this) || this;
  43398. _this.x1 = x1;
  43399. _this.y1 = y1;
  43400. _this.x2 = x2;
  43401. _this.y2 = y2;
  43402. return _this;
  43403. }
  43404. BezierCurveEase.prototype.easeInCore = function (gradient) {
  43405. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  43406. };
  43407. return BezierCurveEase;
  43408. }(EasingFunction));
  43409. BABYLON.BezierCurveEase = BezierCurveEase;
  43410. })(BABYLON || (BABYLON = {}));
  43411. //# sourceMappingURL=babylon.easing.js.map
  43412. var BABYLON;
  43413. (function (BABYLON) {
  43414. var Condition = /** @class */ (function () {
  43415. function Condition(actionManager) {
  43416. this._actionManager = actionManager;
  43417. }
  43418. Condition.prototype.isValid = function () {
  43419. return true;
  43420. };
  43421. Condition.prototype._getProperty = function (propertyPath) {
  43422. return this._actionManager._getProperty(propertyPath);
  43423. };
  43424. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  43425. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43426. };
  43427. Condition.prototype.serialize = function () {
  43428. };
  43429. Condition.prototype._serialize = function (serializedCondition) {
  43430. return {
  43431. type: 2,
  43432. children: [],
  43433. name: serializedCondition.name,
  43434. properties: serializedCondition.properties
  43435. };
  43436. };
  43437. return Condition;
  43438. }());
  43439. BABYLON.Condition = Condition;
  43440. var ValueCondition = /** @class */ (function (_super) {
  43441. __extends(ValueCondition, _super);
  43442. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  43443. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  43444. var _this = _super.call(this, actionManager) || this;
  43445. _this.propertyPath = propertyPath;
  43446. _this.value = value;
  43447. _this.operator = operator;
  43448. _this._target = target;
  43449. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  43450. _this._property = _this._getProperty(_this.propertyPath);
  43451. return _this;
  43452. }
  43453. Object.defineProperty(ValueCondition, "IsEqual", {
  43454. get: function () {
  43455. return ValueCondition._IsEqual;
  43456. },
  43457. enumerable: true,
  43458. configurable: true
  43459. });
  43460. Object.defineProperty(ValueCondition, "IsDifferent", {
  43461. get: function () {
  43462. return ValueCondition._IsDifferent;
  43463. },
  43464. enumerable: true,
  43465. configurable: true
  43466. });
  43467. Object.defineProperty(ValueCondition, "IsGreater", {
  43468. get: function () {
  43469. return ValueCondition._IsGreater;
  43470. },
  43471. enumerable: true,
  43472. configurable: true
  43473. });
  43474. Object.defineProperty(ValueCondition, "IsLesser", {
  43475. get: function () {
  43476. return ValueCondition._IsLesser;
  43477. },
  43478. enumerable: true,
  43479. configurable: true
  43480. });
  43481. // Methods
  43482. ValueCondition.prototype.isValid = function () {
  43483. switch (this.operator) {
  43484. case ValueCondition.IsGreater:
  43485. return this._effectiveTarget[this._property] > this.value;
  43486. case ValueCondition.IsLesser:
  43487. return this._effectiveTarget[this._property] < this.value;
  43488. case ValueCondition.IsEqual:
  43489. case ValueCondition.IsDifferent:
  43490. var check;
  43491. if (this.value.equals) {
  43492. check = this.value.equals(this._effectiveTarget[this._property]);
  43493. }
  43494. else {
  43495. check = this.value === this._effectiveTarget[this._property];
  43496. }
  43497. return this.operator === ValueCondition.IsEqual ? check : !check;
  43498. }
  43499. return false;
  43500. };
  43501. ValueCondition.prototype.serialize = function () {
  43502. return this._serialize({
  43503. name: "ValueCondition",
  43504. properties: [
  43505. BABYLON.Action._GetTargetProperty(this._target),
  43506. { name: "propertyPath", value: this.propertyPath },
  43507. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43508. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  43509. ]
  43510. });
  43511. };
  43512. ValueCondition.GetOperatorName = function (operator) {
  43513. switch (operator) {
  43514. case ValueCondition._IsEqual: return "IsEqual";
  43515. case ValueCondition._IsDifferent: return "IsDifferent";
  43516. case ValueCondition._IsGreater: return "IsGreater";
  43517. case ValueCondition._IsLesser: return "IsLesser";
  43518. default: return "";
  43519. }
  43520. };
  43521. // Statics
  43522. ValueCondition._IsEqual = 0;
  43523. ValueCondition._IsDifferent = 1;
  43524. ValueCondition._IsGreater = 2;
  43525. ValueCondition._IsLesser = 3;
  43526. return ValueCondition;
  43527. }(Condition));
  43528. BABYLON.ValueCondition = ValueCondition;
  43529. var PredicateCondition = /** @class */ (function (_super) {
  43530. __extends(PredicateCondition, _super);
  43531. function PredicateCondition(actionManager, predicate) {
  43532. var _this = _super.call(this, actionManager) || this;
  43533. _this.predicate = predicate;
  43534. return _this;
  43535. }
  43536. PredicateCondition.prototype.isValid = function () {
  43537. return this.predicate();
  43538. };
  43539. return PredicateCondition;
  43540. }(Condition));
  43541. BABYLON.PredicateCondition = PredicateCondition;
  43542. var StateCondition = /** @class */ (function (_super) {
  43543. __extends(StateCondition, _super);
  43544. function StateCondition(actionManager, target, value) {
  43545. var _this = _super.call(this, actionManager) || this;
  43546. _this.value = value;
  43547. _this._target = target;
  43548. return _this;
  43549. }
  43550. // Methods
  43551. StateCondition.prototype.isValid = function () {
  43552. return this._target.state === this.value;
  43553. };
  43554. StateCondition.prototype.serialize = function () {
  43555. return this._serialize({
  43556. name: "StateCondition",
  43557. properties: [
  43558. BABYLON.Action._GetTargetProperty(this._target),
  43559. { name: "value", value: this.value }
  43560. ]
  43561. });
  43562. };
  43563. return StateCondition;
  43564. }(Condition));
  43565. BABYLON.StateCondition = StateCondition;
  43566. })(BABYLON || (BABYLON = {}));
  43567. //# sourceMappingURL=babylon.condition.js.map
  43568. var BABYLON;
  43569. (function (BABYLON) {
  43570. var Action = /** @class */ (function () {
  43571. function Action(triggerOptions, condition) {
  43572. this.triggerOptions = triggerOptions;
  43573. this.onBeforeExecuteObservable = new BABYLON.Observable();
  43574. if (triggerOptions.parameter) {
  43575. this.trigger = triggerOptions.trigger;
  43576. this._triggerParameter = triggerOptions.parameter;
  43577. }
  43578. else {
  43579. this.trigger = triggerOptions;
  43580. }
  43581. this._nextActiveAction = this;
  43582. this._condition = condition;
  43583. }
  43584. // Methods
  43585. Action.prototype._prepare = function () {
  43586. };
  43587. Action.prototype.getTriggerParameter = function () {
  43588. return this._triggerParameter;
  43589. };
  43590. Action.prototype._executeCurrent = function (evt) {
  43591. if (this._nextActiveAction._condition) {
  43592. var condition = this._nextActiveAction._condition;
  43593. var currentRenderId = this._actionManager.getScene().getRenderId();
  43594. // We cache the current evaluation for the current frame
  43595. if (condition._evaluationId === currentRenderId) {
  43596. if (!condition._currentResult) {
  43597. return;
  43598. }
  43599. }
  43600. else {
  43601. condition._evaluationId = currentRenderId;
  43602. if (!condition.isValid()) {
  43603. condition._currentResult = false;
  43604. return;
  43605. }
  43606. condition._currentResult = true;
  43607. }
  43608. }
  43609. this.onBeforeExecuteObservable.notifyObservers(this);
  43610. this._nextActiveAction.execute(evt);
  43611. this.skipToNextActiveAction();
  43612. };
  43613. Action.prototype.execute = function (evt) {
  43614. };
  43615. Action.prototype.skipToNextActiveAction = function () {
  43616. if (this._nextActiveAction._child) {
  43617. if (!this._nextActiveAction._child._actionManager) {
  43618. this._nextActiveAction._child._actionManager = this._actionManager;
  43619. }
  43620. this._nextActiveAction = this._nextActiveAction._child;
  43621. }
  43622. else {
  43623. this._nextActiveAction = this;
  43624. }
  43625. };
  43626. Action.prototype.then = function (action) {
  43627. this._child = action;
  43628. action._actionManager = this._actionManager;
  43629. action._prepare();
  43630. return action;
  43631. };
  43632. Action.prototype._getProperty = function (propertyPath) {
  43633. return this._actionManager._getProperty(propertyPath);
  43634. };
  43635. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  43636. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43637. };
  43638. Action.prototype.serialize = function (parent) {
  43639. };
  43640. // Called by BABYLON.Action objects in serialize(...). Internal use
  43641. Action.prototype._serialize = function (serializedAction, parent) {
  43642. var serializationObject = {
  43643. type: 1,
  43644. children: [],
  43645. name: serializedAction.name,
  43646. properties: serializedAction.properties || []
  43647. };
  43648. // Serialize child
  43649. if (this._child) {
  43650. this._child.serialize(serializationObject);
  43651. }
  43652. // Check if "this" has a condition
  43653. if (this._condition) {
  43654. var serializedCondition = this._condition.serialize();
  43655. serializedCondition.children.push(serializationObject);
  43656. if (parent) {
  43657. parent.children.push(serializedCondition);
  43658. }
  43659. return serializedCondition;
  43660. }
  43661. if (parent) {
  43662. parent.children.push(serializationObject);
  43663. }
  43664. return serializationObject;
  43665. };
  43666. Action._SerializeValueAsString = function (value) {
  43667. if (typeof value === "number") {
  43668. return value.toString();
  43669. }
  43670. if (typeof value === "boolean") {
  43671. return value ? "true" : "false";
  43672. }
  43673. if (value instanceof BABYLON.Vector2) {
  43674. return value.x + ", " + value.y;
  43675. }
  43676. if (value instanceof BABYLON.Vector3) {
  43677. return value.x + ", " + value.y + ", " + value.z;
  43678. }
  43679. if (value instanceof BABYLON.Color3) {
  43680. return value.r + ", " + value.g + ", " + value.b;
  43681. }
  43682. if (value instanceof BABYLON.Color4) {
  43683. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  43684. }
  43685. return value; // string
  43686. };
  43687. Action._GetTargetProperty = function (target) {
  43688. return {
  43689. name: "target",
  43690. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  43691. : target instanceof BABYLON.Light ? "LightProperties"
  43692. : target instanceof BABYLON.Camera ? "CameraProperties"
  43693. : "SceneProperties",
  43694. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  43695. };
  43696. };
  43697. return Action;
  43698. }());
  43699. BABYLON.Action = Action;
  43700. })(BABYLON || (BABYLON = {}));
  43701. //# sourceMappingURL=babylon.action.js.map
  43702. var BABYLON;
  43703. (function (BABYLON) {
  43704. /**
  43705. * ActionEvent is the event beint sent when an action is triggered.
  43706. */
  43707. var ActionEvent = /** @class */ (function () {
  43708. /**
  43709. * @param source The mesh or sprite that triggered the action.
  43710. * @param pointerX The X mouse cursor position at the time of the event
  43711. * @param pointerY The Y mouse cursor position at the time of the event
  43712. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  43713. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  43714. */
  43715. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  43716. this.source = source;
  43717. this.pointerX = pointerX;
  43718. this.pointerY = pointerY;
  43719. this.meshUnderPointer = meshUnderPointer;
  43720. this.sourceEvent = sourceEvent;
  43721. this.additionalData = additionalData;
  43722. }
  43723. /**
  43724. * Helper function to auto-create an ActionEvent from a source mesh.
  43725. * @param source The source mesh that triggered the event
  43726. * @param evt {Event} The original (browser) event
  43727. */
  43728. ActionEvent.CreateNew = function (source, evt, additionalData) {
  43729. var scene = source.getScene();
  43730. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43731. };
  43732. /**
  43733. * Helper function to auto-create an ActionEvent from a source mesh.
  43734. * @param source The source sprite that triggered the event
  43735. * @param scene Scene associated with the sprite
  43736. * @param evt {Event} The original (browser) event
  43737. */
  43738. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  43739. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43740. };
  43741. /**
  43742. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  43743. * @param scene the scene where the event occurred
  43744. * @param evt {Event} The original (browser) event
  43745. */
  43746. ActionEvent.CreateNewFromScene = function (scene, evt) {
  43747. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  43748. };
  43749. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  43750. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  43751. };
  43752. return ActionEvent;
  43753. }());
  43754. BABYLON.ActionEvent = ActionEvent;
  43755. /**
  43756. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  43757. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  43758. */
  43759. var ActionManager = /** @class */ (function () {
  43760. function ActionManager(scene) {
  43761. // Members
  43762. this.actions = new Array();
  43763. this.hoverCursor = '';
  43764. this._scene = scene;
  43765. scene._actionManagers.push(this);
  43766. }
  43767. Object.defineProperty(ActionManager, "NothingTrigger", {
  43768. get: function () {
  43769. return ActionManager._NothingTrigger;
  43770. },
  43771. enumerable: true,
  43772. configurable: true
  43773. });
  43774. Object.defineProperty(ActionManager, "OnPickTrigger", {
  43775. get: function () {
  43776. return ActionManager._OnPickTrigger;
  43777. },
  43778. enumerable: true,
  43779. configurable: true
  43780. });
  43781. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  43782. get: function () {
  43783. return ActionManager._OnLeftPickTrigger;
  43784. },
  43785. enumerable: true,
  43786. configurable: true
  43787. });
  43788. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  43789. get: function () {
  43790. return ActionManager._OnRightPickTrigger;
  43791. },
  43792. enumerable: true,
  43793. configurable: true
  43794. });
  43795. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  43796. get: function () {
  43797. return ActionManager._OnCenterPickTrigger;
  43798. },
  43799. enumerable: true,
  43800. configurable: true
  43801. });
  43802. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  43803. get: function () {
  43804. return ActionManager._OnPickDownTrigger;
  43805. },
  43806. enumerable: true,
  43807. configurable: true
  43808. });
  43809. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  43810. get: function () {
  43811. return ActionManager._OnDoublePickTrigger;
  43812. },
  43813. enumerable: true,
  43814. configurable: true
  43815. });
  43816. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  43817. get: function () {
  43818. return ActionManager._OnPickUpTrigger;
  43819. },
  43820. enumerable: true,
  43821. configurable: true
  43822. });
  43823. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  43824. /// This trigger will only be raised if you also declared a OnPickDown
  43825. get: function () {
  43826. return ActionManager._OnPickOutTrigger;
  43827. },
  43828. enumerable: true,
  43829. configurable: true
  43830. });
  43831. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  43832. get: function () {
  43833. return ActionManager._OnLongPressTrigger;
  43834. },
  43835. enumerable: true,
  43836. configurable: true
  43837. });
  43838. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  43839. get: function () {
  43840. return ActionManager._OnPointerOverTrigger;
  43841. },
  43842. enumerable: true,
  43843. configurable: true
  43844. });
  43845. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  43846. get: function () {
  43847. return ActionManager._OnPointerOutTrigger;
  43848. },
  43849. enumerable: true,
  43850. configurable: true
  43851. });
  43852. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  43853. get: function () {
  43854. return ActionManager._OnEveryFrameTrigger;
  43855. },
  43856. enumerable: true,
  43857. configurable: true
  43858. });
  43859. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  43860. get: function () {
  43861. return ActionManager._OnIntersectionEnterTrigger;
  43862. },
  43863. enumerable: true,
  43864. configurable: true
  43865. });
  43866. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  43867. get: function () {
  43868. return ActionManager._OnIntersectionExitTrigger;
  43869. },
  43870. enumerable: true,
  43871. configurable: true
  43872. });
  43873. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  43874. get: function () {
  43875. return ActionManager._OnKeyDownTrigger;
  43876. },
  43877. enumerable: true,
  43878. configurable: true
  43879. });
  43880. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  43881. get: function () {
  43882. return ActionManager._OnKeyUpTrigger;
  43883. },
  43884. enumerable: true,
  43885. configurable: true
  43886. });
  43887. // Methods
  43888. ActionManager.prototype.dispose = function () {
  43889. var index = this._scene._actionManagers.indexOf(this);
  43890. for (var i = 0; i < this.actions.length; i++) {
  43891. var action = this.actions[i];
  43892. ActionManager.Triggers[action.trigger]--;
  43893. if (ActionManager.Triggers[action.trigger] === 0) {
  43894. delete ActionManager.Triggers[action.trigger];
  43895. }
  43896. }
  43897. if (index > -1) {
  43898. this._scene._actionManagers.splice(index, 1);
  43899. }
  43900. };
  43901. ActionManager.prototype.getScene = function () {
  43902. return this._scene;
  43903. };
  43904. /**
  43905. * Does this action manager handles actions of any of the given triggers
  43906. * @param {number[]} triggers - the triggers to be tested
  43907. * @return {boolean} whether one (or more) of the triggers is handeled
  43908. */
  43909. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  43910. for (var index = 0; index < this.actions.length; index++) {
  43911. var action = this.actions[index];
  43912. if (triggers.indexOf(action.trigger) > -1) {
  43913. return true;
  43914. }
  43915. }
  43916. return false;
  43917. };
  43918. /**
  43919. * Does this action manager handles actions of a given trigger
  43920. * @param {number} trigger - the trigger to be tested
  43921. * @return {boolean} whether the trigger is handeled
  43922. */
  43923. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  43924. for (var index = 0; index < this.actions.length; index++) {
  43925. var action = this.actions[index];
  43926. if (action.trigger === trigger) {
  43927. return true;
  43928. }
  43929. }
  43930. return false;
  43931. };
  43932. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  43933. /**
  43934. * Does this action manager has pointer triggers
  43935. * @return {boolean} whether or not it has pointer triggers
  43936. */
  43937. get: function () {
  43938. for (var index = 0; index < this.actions.length; index++) {
  43939. var action = this.actions[index];
  43940. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  43941. return true;
  43942. }
  43943. }
  43944. return false;
  43945. },
  43946. enumerable: true,
  43947. configurable: true
  43948. });
  43949. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  43950. /**
  43951. * Does this action manager has pick triggers
  43952. * @return {boolean} whether or not it has pick triggers
  43953. */
  43954. get: function () {
  43955. for (var index = 0; index < this.actions.length; index++) {
  43956. var action = this.actions[index];
  43957. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  43958. return true;
  43959. }
  43960. }
  43961. return false;
  43962. },
  43963. enumerable: true,
  43964. configurable: true
  43965. });
  43966. Object.defineProperty(ActionManager, "HasTriggers", {
  43967. /**
  43968. * Does exist one action manager with at least one trigger
  43969. * @return {boolean} whether or not it exists one action manager with one trigger
  43970. **/
  43971. get: function () {
  43972. for (var t in ActionManager.Triggers) {
  43973. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43974. return true;
  43975. }
  43976. }
  43977. return false;
  43978. },
  43979. enumerable: true,
  43980. configurable: true
  43981. });
  43982. Object.defineProperty(ActionManager, "HasPickTriggers", {
  43983. /**
  43984. * Does exist one action manager with at least one pick trigger
  43985. * @return {boolean} whether or not it exists one action manager with one pick trigger
  43986. **/
  43987. get: function () {
  43988. for (var t in ActionManager.Triggers) {
  43989. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43990. var t_int = parseInt(t);
  43991. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  43992. return true;
  43993. }
  43994. }
  43995. }
  43996. return false;
  43997. },
  43998. enumerable: true,
  43999. configurable: true
  44000. });
  44001. /**
  44002. * Does exist one action manager that handles actions of a given trigger
  44003. * @param {number} trigger - the trigger to be tested
  44004. * @return {boolean} whether the trigger is handeled by at least one action manager
  44005. **/
  44006. ActionManager.HasSpecificTrigger = function (trigger) {
  44007. for (var t in ActionManager.Triggers) {
  44008. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44009. var t_int = parseInt(t);
  44010. if (t_int === trigger) {
  44011. return true;
  44012. }
  44013. }
  44014. }
  44015. return false;
  44016. };
  44017. /**
  44018. * Registers an action to this action manager
  44019. * @param {BABYLON.Action} action - the action to be registered
  44020. * @return {BABYLON.Action} the action amended (prepared) after registration
  44021. */
  44022. ActionManager.prototype.registerAction = function (action) {
  44023. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  44024. if (this.getScene().actionManager !== this) {
  44025. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  44026. return null;
  44027. }
  44028. }
  44029. this.actions.push(action);
  44030. if (ActionManager.Triggers[action.trigger]) {
  44031. ActionManager.Triggers[action.trigger]++;
  44032. }
  44033. else {
  44034. ActionManager.Triggers[action.trigger] = 1;
  44035. }
  44036. action._actionManager = this;
  44037. action._prepare();
  44038. return action;
  44039. };
  44040. /**
  44041. * Process a specific trigger
  44042. * @param {number} trigger - the trigger to process
  44043. * @param evt {BABYLON.ActionEvent} the event details to be processed
  44044. */
  44045. ActionManager.prototype.processTrigger = function (trigger, evt) {
  44046. for (var index = 0; index < this.actions.length; index++) {
  44047. var action = this.actions[index];
  44048. if (action.trigger === trigger) {
  44049. if (evt) {
  44050. if (trigger === ActionManager.OnKeyUpTrigger
  44051. || trigger === ActionManager.OnKeyDownTrigger) {
  44052. var parameter = action.getTriggerParameter();
  44053. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  44054. if (!parameter.toLowerCase) {
  44055. continue;
  44056. }
  44057. var lowerCase = parameter.toLowerCase();
  44058. if (lowerCase !== evt.sourceEvent.key) {
  44059. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  44060. var actualkey = String.fromCharCode(unicode).toLowerCase();
  44061. if (actualkey !== lowerCase) {
  44062. continue;
  44063. }
  44064. }
  44065. }
  44066. }
  44067. }
  44068. action._executeCurrent(evt);
  44069. }
  44070. }
  44071. };
  44072. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  44073. var properties = propertyPath.split(".");
  44074. for (var index = 0; index < properties.length - 1; index++) {
  44075. target = target[properties[index]];
  44076. }
  44077. return target;
  44078. };
  44079. ActionManager.prototype._getProperty = function (propertyPath) {
  44080. var properties = propertyPath.split(".");
  44081. return properties[properties.length - 1];
  44082. };
  44083. ActionManager.prototype.serialize = function (name) {
  44084. var root = {
  44085. children: new Array(),
  44086. name: name,
  44087. type: 3,
  44088. properties: new Array() // Empty for root but required
  44089. };
  44090. for (var i = 0; i < this.actions.length; i++) {
  44091. var triggerObject = {
  44092. type: 0,
  44093. children: new Array(),
  44094. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  44095. properties: new Array()
  44096. };
  44097. var triggerOptions = this.actions[i].triggerOptions;
  44098. if (triggerOptions && typeof triggerOptions !== "number") {
  44099. if (triggerOptions.parameter instanceof BABYLON.Node) {
  44100. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  44101. }
  44102. else {
  44103. var parameter = {};
  44104. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  44105. if (triggerOptions.parameter.mesh) {
  44106. parameter._meshId = triggerOptions.parameter.mesh.id;
  44107. }
  44108. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  44109. }
  44110. }
  44111. // Serialize child action, recursively
  44112. this.actions[i].serialize(triggerObject);
  44113. // Add serialized trigger
  44114. root.children.push(triggerObject);
  44115. }
  44116. return root;
  44117. };
  44118. ActionManager.Parse = function (parsedActions, object, scene) {
  44119. var actionManager = new ActionManager(scene);
  44120. if (object === null)
  44121. scene.actionManager = actionManager;
  44122. else
  44123. object.actionManager = actionManager;
  44124. // instanciate a new object
  44125. var instanciate = function (name, params) {
  44126. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  44127. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  44128. newInstance.constructor.apply(newInstance, params);
  44129. return newInstance;
  44130. };
  44131. var parseParameter = function (name, value, target, propertyPath) {
  44132. if (propertyPath === null) {
  44133. // String, boolean or float
  44134. var floatValue = parseFloat(value);
  44135. if (value === "true" || value === "false")
  44136. return value === "true";
  44137. else
  44138. return isNaN(floatValue) ? value : floatValue;
  44139. }
  44140. var effectiveTarget = propertyPath.split(".");
  44141. var values = value.split(",");
  44142. // Get effective Target
  44143. for (var i = 0; i < effectiveTarget.length; i++) {
  44144. target = target[effectiveTarget[i]];
  44145. }
  44146. // Return appropriate value with its type
  44147. if (typeof (target) === "boolean")
  44148. return values[0] === "true";
  44149. if (typeof (target) === "string")
  44150. return values[0];
  44151. // Parameters with multiple values such as Vector3 etc.
  44152. var split = new Array();
  44153. for (var i = 0; i < values.length; i++)
  44154. split.push(parseFloat(values[i]));
  44155. if (target instanceof BABYLON.Vector3)
  44156. return BABYLON.Vector3.FromArray(split);
  44157. if (target instanceof BABYLON.Vector4)
  44158. return BABYLON.Vector4.FromArray(split);
  44159. if (target instanceof BABYLON.Color3)
  44160. return BABYLON.Color3.FromArray(split);
  44161. if (target instanceof BABYLON.Color4)
  44162. return BABYLON.Color4.FromArray(split);
  44163. return parseFloat(values[0]);
  44164. };
  44165. // traverse graph per trigger
  44166. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  44167. if (combineArray === void 0) { combineArray = null; }
  44168. if (parsedAction.detached)
  44169. return;
  44170. var parameters = new Array();
  44171. var target = null;
  44172. var propertyPath = null;
  44173. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  44174. // Parameters
  44175. if (parsedAction.type === 2)
  44176. parameters.push(actionManager);
  44177. else
  44178. parameters.push(trigger);
  44179. if (combine) {
  44180. var actions = new Array();
  44181. for (var j = 0; j < parsedAction.combine.length; j++) {
  44182. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  44183. }
  44184. parameters.push(actions);
  44185. }
  44186. else {
  44187. for (var i = 0; i < parsedAction.properties.length; i++) {
  44188. var value = parsedAction.properties[i].value;
  44189. var name = parsedAction.properties[i].name;
  44190. var targetType = parsedAction.properties[i].targetType;
  44191. if (name === "target")
  44192. if (targetType !== null && targetType === "SceneProperties")
  44193. value = target = scene;
  44194. else
  44195. value = target = scene.getNodeByName(value);
  44196. else if (name === "parent")
  44197. value = scene.getNodeByName(value);
  44198. else if (name === "sound")
  44199. value = scene.getSoundByName(value);
  44200. else if (name !== "propertyPath") {
  44201. if (parsedAction.type === 2 && name === "operator")
  44202. value = BABYLON.ValueCondition[value];
  44203. else
  44204. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  44205. }
  44206. else {
  44207. propertyPath = value;
  44208. }
  44209. parameters.push(value);
  44210. }
  44211. }
  44212. if (combineArray === null) {
  44213. parameters.push(condition);
  44214. }
  44215. else {
  44216. parameters.push(null);
  44217. }
  44218. // If interpolate value action
  44219. if (parsedAction.name === "InterpolateValueAction") {
  44220. var param = parameters[parameters.length - 2];
  44221. parameters[parameters.length - 1] = param;
  44222. parameters[parameters.length - 2] = condition;
  44223. }
  44224. // Action or condition(s) and not CombineAction
  44225. var newAction = instanciate(parsedAction.name, parameters);
  44226. if (newAction instanceof BABYLON.Condition && condition !== null) {
  44227. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  44228. if (action)
  44229. action.then(nothing);
  44230. else
  44231. actionManager.registerAction(nothing);
  44232. action = nothing;
  44233. }
  44234. if (combineArray === null) {
  44235. if (newAction instanceof BABYLON.Condition) {
  44236. condition = newAction;
  44237. newAction = action;
  44238. }
  44239. else {
  44240. condition = null;
  44241. if (action)
  44242. action.then(newAction);
  44243. else
  44244. actionManager.registerAction(newAction);
  44245. }
  44246. }
  44247. else {
  44248. combineArray.push(newAction);
  44249. }
  44250. for (var i = 0; i < parsedAction.children.length; i++)
  44251. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  44252. };
  44253. // triggers
  44254. for (var i = 0; i < parsedActions.children.length; i++) {
  44255. var triggerParams;
  44256. var trigger = parsedActions.children[i];
  44257. if (trigger.properties.length > 0) {
  44258. var param = trigger.properties[0].value;
  44259. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  44260. if (value._meshId) {
  44261. value.mesh = scene.getMeshByID(value._meshId);
  44262. }
  44263. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  44264. }
  44265. else
  44266. triggerParams = ActionManager[trigger.name];
  44267. for (var j = 0; j < trigger.children.length; j++) {
  44268. if (!trigger.detached)
  44269. traverse(trigger.children[j], triggerParams, null, null);
  44270. }
  44271. }
  44272. };
  44273. ActionManager.GetTriggerName = function (trigger) {
  44274. switch (trigger) {
  44275. case 0: return "NothingTrigger";
  44276. case 1: return "OnPickTrigger";
  44277. case 2: return "OnLeftPickTrigger";
  44278. case 3: return "OnRightPickTrigger";
  44279. case 4: return "OnCenterPickTrigger";
  44280. case 5: return "OnPickDownTrigger";
  44281. case 6: return "OnPickUpTrigger";
  44282. case 7: return "OnLongPressTrigger";
  44283. case 8: return "OnPointerOverTrigger";
  44284. case 9: return "OnPointerOutTrigger";
  44285. case 10: return "OnEveryFrameTrigger";
  44286. case 11: return "OnIntersectionEnterTrigger";
  44287. case 12: return "OnIntersectionExitTrigger";
  44288. case 13: return "OnKeyDownTrigger";
  44289. case 14: return "OnKeyUpTrigger";
  44290. case 15: return "OnPickOutTrigger";
  44291. default: return "";
  44292. }
  44293. };
  44294. // Statics
  44295. ActionManager._NothingTrigger = 0;
  44296. ActionManager._OnPickTrigger = 1;
  44297. ActionManager._OnLeftPickTrigger = 2;
  44298. ActionManager._OnRightPickTrigger = 3;
  44299. ActionManager._OnCenterPickTrigger = 4;
  44300. ActionManager._OnPickDownTrigger = 5;
  44301. ActionManager._OnDoublePickTrigger = 6;
  44302. ActionManager._OnPickUpTrigger = 7;
  44303. ActionManager._OnLongPressTrigger = 8;
  44304. ActionManager._OnPointerOverTrigger = 9;
  44305. ActionManager._OnPointerOutTrigger = 10;
  44306. ActionManager._OnEveryFrameTrigger = 11;
  44307. ActionManager._OnIntersectionEnterTrigger = 12;
  44308. ActionManager._OnIntersectionExitTrigger = 13;
  44309. ActionManager._OnKeyDownTrigger = 14;
  44310. ActionManager._OnKeyUpTrigger = 15;
  44311. ActionManager._OnPickOutTrigger = 16;
  44312. ActionManager.Triggers = {};
  44313. return ActionManager;
  44314. }());
  44315. BABYLON.ActionManager = ActionManager;
  44316. })(BABYLON || (BABYLON = {}));
  44317. //# sourceMappingURL=babylon.actionManager.js.map
  44318. var BABYLON;
  44319. (function (BABYLON) {
  44320. var InterpolateValueAction = /** @class */ (function (_super) {
  44321. __extends(InterpolateValueAction, _super);
  44322. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  44323. if (duration === void 0) { duration = 1000; }
  44324. var _this = _super.call(this, triggerOptions, condition) || this;
  44325. _this.propertyPath = propertyPath;
  44326. _this.value = value;
  44327. _this.duration = duration;
  44328. _this.stopOtherAnimations = stopOtherAnimations;
  44329. _this.onInterpolationDone = onInterpolationDone;
  44330. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  44331. _this._target = _this._effectiveTarget = target;
  44332. return _this;
  44333. }
  44334. InterpolateValueAction.prototype._prepare = function () {
  44335. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44336. this._property = this._getProperty(this.propertyPath);
  44337. };
  44338. InterpolateValueAction.prototype.execute = function () {
  44339. var _this = this;
  44340. var scene = this._actionManager.getScene();
  44341. var keys = [
  44342. {
  44343. frame: 0,
  44344. value: this._effectiveTarget[this._property]
  44345. }, {
  44346. frame: 100,
  44347. value: this.value
  44348. }
  44349. ];
  44350. var dataType;
  44351. if (typeof this.value === "number") {
  44352. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  44353. }
  44354. else if (this.value instanceof BABYLON.Color3) {
  44355. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  44356. }
  44357. else if (this.value instanceof BABYLON.Vector3) {
  44358. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  44359. }
  44360. else if (this.value instanceof BABYLON.Matrix) {
  44361. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  44362. }
  44363. else if (this.value instanceof BABYLON.Quaternion) {
  44364. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  44365. }
  44366. else {
  44367. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  44368. return;
  44369. }
  44370. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  44371. animation.setKeys(keys);
  44372. if (this.stopOtherAnimations) {
  44373. scene.stopAnimation(this._effectiveTarget);
  44374. }
  44375. var wrapper = function () {
  44376. _this.onInterpolationDoneObservable.notifyObservers(_this);
  44377. if (_this.onInterpolationDone) {
  44378. _this.onInterpolationDone();
  44379. }
  44380. };
  44381. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  44382. };
  44383. InterpolateValueAction.prototype.serialize = function (parent) {
  44384. return _super.prototype._serialize.call(this, {
  44385. name: "InterpolateValueAction",
  44386. properties: [
  44387. BABYLON.Action._GetTargetProperty(this._target),
  44388. { name: "propertyPath", value: this.propertyPath },
  44389. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44390. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  44391. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  44392. ]
  44393. }, parent);
  44394. };
  44395. return InterpolateValueAction;
  44396. }(BABYLON.Action));
  44397. BABYLON.InterpolateValueAction = InterpolateValueAction;
  44398. })(BABYLON || (BABYLON = {}));
  44399. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  44400. var BABYLON;
  44401. (function (BABYLON) {
  44402. var SwitchBooleanAction = /** @class */ (function (_super) {
  44403. __extends(SwitchBooleanAction, _super);
  44404. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  44405. var _this = _super.call(this, triggerOptions, condition) || this;
  44406. _this.propertyPath = propertyPath;
  44407. _this._target = _this._effectiveTarget = target;
  44408. return _this;
  44409. }
  44410. SwitchBooleanAction.prototype._prepare = function () {
  44411. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44412. this._property = this._getProperty(this.propertyPath);
  44413. };
  44414. SwitchBooleanAction.prototype.execute = function () {
  44415. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  44416. };
  44417. SwitchBooleanAction.prototype.serialize = function (parent) {
  44418. return _super.prototype._serialize.call(this, {
  44419. name: "SwitchBooleanAction",
  44420. properties: [
  44421. BABYLON.Action._GetTargetProperty(this._target),
  44422. { name: "propertyPath", value: this.propertyPath }
  44423. ]
  44424. }, parent);
  44425. };
  44426. return SwitchBooleanAction;
  44427. }(BABYLON.Action));
  44428. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  44429. var SetStateAction = /** @class */ (function (_super) {
  44430. __extends(SetStateAction, _super);
  44431. function SetStateAction(triggerOptions, target, value, condition) {
  44432. var _this = _super.call(this, triggerOptions, condition) || this;
  44433. _this.value = value;
  44434. _this._target = target;
  44435. return _this;
  44436. }
  44437. SetStateAction.prototype.execute = function () {
  44438. this._target.state = this.value;
  44439. };
  44440. SetStateAction.prototype.serialize = function (parent) {
  44441. return _super.prototype._serialize.call(this, {
  44442. name: "SetStateAction",
  44443. properties: [
  44444. BABYLON.Action._GetTargetProperty(this._target),
  44445. { name: "value", value: this.value }
  44446. ]
  44447. }, parent);
  44448. };
  44449. return SetStateAction;
  44450. }(BABYLON.Action));
  44451. BABYLON.SetStateAction = SetStateAction;
  44452. var SetValueAction = /** @class */ (function (_super) {
  44453. __extends(SetValueAction, _super);
  44454. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  44455. var _this = _super.call(this, triggerOptions, condition) || this;
  44456. _this.propertyPath = propertyPath;
  44457. _this.value = value;
  44458. _this._target = _this._effectiveTarget = target;
  44459. return _this;
  44460. }
  44461. SetValueAction.prototype._prepare = function () {
  44462. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44463. this._property = this._getProperty(this.propertyPath);
  44464. };
  44465. SetValueAction.prototype.execute = function () {
  44466. this._effectiveTarget[this._property] = this.value;
  44467. if (this._target.markAsDirty) {
  44468. this._target.markAsDirty(this._property);
  44469. }
  44470. };
  44471. SetValueAction.prototype.serialize = function (parent) {
  44472. return _super.prototype._serialize.call(this, {
  44473. name: "SetValueAction",
  44474. properties: [
  44475. BABYLON.Action._GetTargetProperty(this._target),
  44476. { name: "propertyPath", value: this.propertyPath },
  44477. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44478. ]
  44479. }, parent);
  44480. };
  44481. return SetValueAction;
  44482. }(BABYLON.Action));
  44483. BABYLON.SetValueAction = SetValueAction;
  44484. var IncrementValueAction = /** @class */ (function (_super) {
  44485. __extends(IncrementValueAction, _super);
  44486. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  44487. var _this = _super.call(this, triggerOptions, condition) || this;
  44488. _this.propertyPath = propertyPath;
  44489. _this.value = value;
  44490. _this._target = _this._effectiveTarget = target;
  44491. return _this;
  44492. }
  44493. IncrementValueAction.prototype._prepare = function () {
  44494. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44495. this._property = this._getProperty(this.propertyPath);
  44496. if (typeof this._effectiveTarget[this._property] !== "number") {
  44497. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  44498. }
  44499. };
  44500. IncrementValueAction.prototype.execute = function () {
  44501. this._effectiveTarget[this._property] += this.value;
  44502. if (this._target.markAsDirty) {
  44503. this._target.markAsDirty(this._property);
  44504. }
  44505. };
  44506. IncrementValueAction.prototype.serialize = function (parent) {
  44507. return _super.prototype._serialize.call(this, {
  44508. name: "IncrementValueAction",
  44509. properties: [
  44510. BABYLON.Action._GetTargetProperty(this._target),
  44511. { name: "propertyPath", value: this.propertyPath },
  44512. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44513. ]
  44514. }, parent);
  44515. };
  44516. return IncrementValueAction;
  44517. }(BABYLON.Action));
  44518. BABYLON.IncrementValueAction = IncrementValueAction;
  44519. var PlayAnimationAction = /** @class */ (function (_super) {
  44520. __extends(PlayAnimationAction, _super);
  44521. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  44522. var _this = _super.call(this, triggerOptions, condition) || this;
  44523. _this.from = from;
  44524. _this.to = to;
  44525. _this.loop = loop;
  44526. _this._target = target;
  44527. return _this;
  44528. }
  44529. PlayAnimationAction.prototype._prepare = function () {
  44530. };
  44531. PlayAnimationAction.prototype.execute = function () {
  44532. var scene = this._actionManager.getScene();
  44533. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  44534. };
  44535. PlayAnimationAction.prototype.serialize = function (parent) {
  44536. return _super.prototype._serialize.call(this, {
  44537. name: "PlayAnimationAction",
  44538. properties: [
  44539. BABYLON.Action._GetTargetProperty(this._target),
  44540. { name: "from", value: String(this.from) },
  44541. { name: "to", value: String(this.to) },
  44542. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  44543. ]
  44544. }, parent);
  44545. };
  44546. return PlayAnimationAction;
  44547. }(BABYLON.Action));
  44548. BABYLON.PlayAnimationAction = PlayAnimationAction;
  44549. var StopAnimationAction = /** @class */ (function (_super) {
  44550. __extends(StopAnimationAction, _super);
  44551. function StopAnimationAction(triggerOptions, target, condition) {
  44552. var _this = _super.call(this, triggerOptions, condition) || this;
  44553. _this._target = target;
  44554. return _this;
  44555. }
  44556. StopAnimationAction.prototype._prepare = function () {
  44557. };
  44558. StopAnimationAction.prototype.execute = function () {
  44559. var scene = this._actionManager.getScene();
  44560. scene.stopAnimation(this._target);
  44561. };
  44562. StopAnimationAction.prototype.serialize = function (parent) {
  44563. return _super.prototype._serialize.call(this, {
  44564. name: "StopAnimationAction",
  44565. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  44566. }, parent);
  44567. };
  44568. return StopAnimationAction;
  44569. }(BABYLON.Action));
  44570. BABYLON.StopAnimationAction = StopAnimationAction;
  44571. var DoNothingAction = /** @class */ (function (_super) {
  44572. __extends(DoNothingAction, _super);
  44573. function DoNothingAction(triggerOptions, condition) {
  44574. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  44575. return _super.call(this, triggerOptions, condition) || this;
  44576. }
  44577. DoNothingAction.prototype.execute = function () {
  44578. };
  44579. DoNothingAction.prototype.serialize = function (parent) {
  44580. return _super.prototype._serialize.call(this, {
  44581. name: "DoNothingAction",
  44582. properties: []
  44583. }, parent);
  44584. };
  44585. return DoNothingAction;
  44586. }(BABYLON.Action));
  44587. BABYLON.DoNothingAction = DoNothingAction;
  44588. var CombineAction = /** @class */ (function (_super) {
  44589. __extends(CombineAction, _super);
  44590. function CombineAction(triggerOptions, children, condition) {
  44591. var _this = _super.call(this, triggerOptions, condition) || this;
  44592. _this.children = children;
  44593. return _this;
  44594. }
  44595. CombineAction.prototype._prepare = function () {
  44596. for (var index = 0; index < this.children.length; index++) {
  44597. this.children[index]._actionManager = this._actionManager;
  44598. this.children[index]._prepare();
  44599. }
  44600. };
  44601. CombineAction.prototype.execute = function (evt) {
  44602. for (var index = 0; index < this.children.length; index++) {
  44603. this.children[index].execute(evt);
  44604. }
  44605. };
  44606. CombineAction.prototype.serialize = function (parent) {
  44607. var serializationObject = _super.prototype._serialize.call(this, {
  44608. name: "CombineAction",
  44609. properties: [],
  44610. combine: []
  44611. }, parent);
  44612. for (var i = 0; i < this.children.length; i++) {
  44613. serializationObject.combine.push(this.children[i].serialize(null));
  44614. }
  44615. return serializationObject;
  44616. };
  44617. return CombineAction;
  44618. }(BABYLON.Action));
  44619. BABYLON.CombineAction = CombineAction;
  44620. var ExecuteCodeAction = /** @class */ (function (_super) {
  44621. __extends(ExecuteCodeAction, _super);
  44622. function ExecuteCodeAction(triggerOptions, func, condition) {
  44623. var _this = _super.call(this, triggerOptions, condition) || this;
  44624. _this.func = func;
  44625. return _this;
  44626. }
  44627. ExecuteCodeAction.prototype.execute = function (evt) {
  44628. this.func(evt);
  44629. };
  44630. return ExecuteCodeAction;
  44631. }(BABYLON.Action));
  44632. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  44633. var SetParentAction = /** @class */ (function (_super) {
  44634. __extends(SetParentAction, _super);
  44635. function SetParentAction(triggerOptions, target, parent, condition) {
  44636. var _this = _super.call(this, triggerOptions, condition) || this;
  44637. _this._target = target;
  44638. _this._parent = parent;
  44639. return _this;
  44640. }
  44641. SetParentAction.prototype._prepare = function () {
  44642. };
  44643. SetParentAction.prototype.execute = function () {
  44644. if (this._target.parent === this._parent) {
  44645. return;
  44646. }
  44647. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  44648. invertParentWorldMatrix.invert();
  44649. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  44650. this._target.parent = this._parent;
  44651. };
  44652. SetParentAction.prototype.serialize = function (parent) {
  44653. return _super.prototype._serialize.call(this, {
  44654. name: "SetParentAction",
  44655. properties: [
  44656. BABYLON.Action._GetTargetProperty(this._target),
  44657. BABYLON.Action._GetTargetProperty(this._parent),
  44658. ]
  44659. }, parent);
  44660. };
  44661. return SetParentAction;
  44662. }(BABYLON.Action));
  44663. BABYLON.SetParentAction = SetParentAction;
  44664. var PlaySoundAction = /** @class */ (function (_super) {
  44665. __extends(PlaySoundAction, _super);
  44666. function PlaySoundAction(triggerOptions, sound, condition) {
  44667. var _this = _super.call(this, triggerOptions, condition) || this;
  44668. _this._sound = sound;
  44669. return _this;
  44670. }
  44671. PlaySoundAction.prototype._prepare = function () {
  44672. };
  44673. PlaySoundAction.prototype.execute = function () {
  44674. if (this._sound !== undefined)
  44675. this._sound.play();
  44676. };
  44677. PlaySoundAction.prototype.serialize = function (parent) {
  44678. return _super.prototype._serialize.call(this, {
  44679. name: "PlaySoundAction",
  44680. properties: [{ name: "sound", value: this._sound.name }]
  44681. }, parent);
  44682. };
  44683. return PlaySoundAction;
  44684. }(BABYLON.Action));
  44685. BABYLON.PlaySoundAction = PlaySoundAction;
  44686. var StopSoundAction = /** @class */ (function (_super) {
  44687. __extends(StopSoundAction, _super);
  44688. function StopSoundAction(triggerOptions, sound, condition) {
  44689. var _this = _super.call(this, triggerOptions, condition) || this;
  44690. _this._sound = sound;
  44691. return _this;
  44692. }
  44693. StopSoundAction.prototype._prepare = function () {
  44694. };
  44695. StopSoundAction.prototype.execute = function () {
  44696. if (this._sound !== undefined)
  44697. this._sound.stop();
  44698. };
  44699. StopSoundAction.prototype.serialize = function (parent) {
  44700. return _super.prototype._serialize.call(this, {
  44701. name: "StopSoundAction",
  44702. properties: [{ name: "sound", value: this._sound.name }]
  44703. }, parent);
  44704. };
  44705. return StopSoundAction;
  44706. }(BABYLON.Action));
  44707. BABYLON.StopSoundAction = StopSoundAction;
  44708. })(BABYLON || (BABYLON = {}));
  44709. //# sourceMappingURL=babylon.directActions.js.map
  44710. var BABYLON;
  44711. (function (BABYLON) {
  44712. var SpriteManager = /** @class */ (function () {
  44713. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  44714. if (epsilon === void 0) { epsilon = 0.01; }
  44715. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44716. this.name = name;
  44717. this.sprites = new Array();
  44718. this.renderingGroupId = 0;
  44719. this.layerMask = 0x0FFFFFFF;
  44720. this.fogEnabled = true;
  44721. this.isPickable = false;
  44722. /**
  44723. * An event triggered when the manager is disposed.
  44724. * @type {BABYLON.Observable}
  44725. */
  44726. this.onDisposeObservable = new BABYLON.Observable();
  44727. this._vertexBuffers = {};
  44728. this._capacity = capacity;
  44729. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  44730. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44731. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44732. if (cellSize.width && cellSize.height) {
  44733. this.cellWidth = cellSize.width;
  44734. this.cellHeight = cellSize.height;
  44735. }
  44736. else if (cellSize !== undefined) {
  44737. this.cellWidth = cellSize;
  44738. this.cellHeight = cellSize;
  44739. }
  44740. else {
  44741. return;
  44742. }
  44743. this._epsilon = epsilon;
  44744. this._scene = scene;
  44745. this._scene.spriteManagers.push(this);
  44746. var indices = [];
  44747. var index = 0;
  44748. for (var count = 0; count < capacity; count++) {
  44749. indices.push(index);
  44750. indices.push(index + 1);
  44751. indices.push(index + 2);
  44752. indices.push(index);
  44753. indices.push(index + 2);
  44754. indices.push(index + 3);
  44755. index += 4;
  44756. }
  44757. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  44758. // VBO
  44759. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  44760. this._vertexData = new Float32Array(capacity * 16 * 4);
  44761. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  44762. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  44763. var options = this._buffer.createVertexBuffer("options", 4, 4);
  44764. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  44765. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  44766. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44767. this._vertexBuffers["options"] = options;
  44768. this._vertexBuffers["cellInfo"] = cellInfo;
  44769. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44770. // Effects
  44771. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  44772. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  44773. }
  44774. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  44775. set: function (callback) {
  44776. if (this._onDisposeObserver) {
  44777. this.onDisposeObservable.remove(this._onDisposeObserver);
  44778. }
  44779. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44780. },
  44781. enumerable: true,
  44782. configurable: true
  44783. });
  44784. Object.defineProperty(SpriteManager.prototype, "texture", {
  44785. get: function () {
  44786. return this._spriteTexture;
  44787. },
  44788. set: function (value) {
  44789. this._spriteTexture = value;
  44790. },
  44791. enumerable: true,
  44792. configurable: true
  44793. });
  44794. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  44795. var arrayOffset = index * 16;
  44796. if (offsetX === 0)
  44797. offsetX = this._epsilon;
  44798. else if (offsetX === 1)
  44799. offsetX = 1 - this._epsilon;
  44800. if (offsetY === 0)
  44801. offsetY = this._epsilon;
  44802. else if (offsetY === 1)
  44803. offsetY = 1 - this._epsilon;
  44804. this._vertexData[arrayOffset] = sprite.position.x;
  44805. this._vertexData[arrayOffset + 1] = sprite.position.y;
  44806. this._vertexData[arrayOffset + 2] = sprite.position.z;
  44807. this._vertexData[arrayOffset + 3] = sprite.angle;
  44808. this._vertexData[arrayOffset + 4] = sprite.width;
  44809. this._vertexData[arrayOffset + 5] = sprite.height;
  44810. this._vertexData[arrayOffset + 6] = offsetX;
  44811. this._vertexData[arrayOffset + 7] = offsetY;
  44812. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  44813. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  44814. var offset = (sprite.cellIndex / rowSize) >> 0;
  44815. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  44816. this._vertexData[arrayOffset + 11] = offset;
  44817. // Color
  44818. this._vertexData[arrayOffset + 12] = sprite.color.r;
  44819. this._vertexData[arrayOffset + 13] = sprite.color.g;
  44820. this._vertexData[arrayOffset + 14] = sprite.color.b;
  44821. this._vertexData[arrayOffset + 15] = sprite.color.a;
  44822. };
  44823. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  44824. var count = Math.min(this._capacity, this.sprites.length);
  44825. var min = BABYLON.Vector3.Zero();
  44826. var max = BABYLON.Vector3.Zero();
  44827. var distance = Number.MAX_VALUE;
  44828. var currentSprite = null;
  44829. var cameraSpacePosition = BABYLON.Vector3.Zero();
  44830. var cameraView = camera.getViewMatrix();
  44831. for (var index = 0; index < count; index++) {
  44832. var sprite = this.sprites[index];
  44833. if (!sprite) {
  44834. continue;
  44835. }
  44836. if (predicate) {
  44837. if (!predicate(sprite)) {
  44838. continue;
  44839. }
  44840. }
  44841. else if (!sprite.isPickable) {
  44842. continue;
  44843. }
  44844. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  44845. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  44846. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  44847. if (ray.intersectsBoxMinMax(min, max)) {
  44848. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  44849. if (distance > currentDistance) {
  44850. distance = currentDistance;
  44851. currentSprite = sprite;
  44852. if (fastCheck) {
  44853. break;
  44854. }
  44855. }
  44856. }
  44857. }
  44858. if (currentSprite) {
  44859. var result = new BABYLON.PickingInfo();
  44860. result.hit = true;
  44861. result.pickedSprite = currentSprite;
  44862. result.distance = distance;
  44863. return result;
  44864. }
  44865. return null;
  44866. };
  44867. SpriteManager.prototype.render = function () {
  44868. // Check
  44869. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  44870. return;
  44871. var engine = this._scene.getEngine();
  44872. var baseSize = this._spriteTexture.getBaseSize();
  44873. // Sprites
  44874. var deltaTime = engine.getDeltaTime();
  44875. var max = Math.min(this._capacity, this.sprites.length);
  44876. var rowSize = baseSize.width / this.cellWidth;
  44877. var offset = 0;
  44878. for (var index = 0; index < max; index++) {
  44879. var sprite = this.sprites[index];
  44880. if (!sprite) {
  44881. continue;
  44882. }
  44883. sprite._animate(deltaTime);
  44884. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  44885. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  44886. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  44887. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  44888. }
  44889. this._buffer.update(this._vertexData);
  44890. // Render
  44891. var effect = this._effectBase;
  44892. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44893. effect = this._effectFog;
  44894. }
  44895. engine.enableEffect(effect);
  44896. var viewMatrix = this._scene.getViewMatrix();
  44897. effect.setTexture("diffuseSampler", this._spriteTexture);
  44898. effect.setMatrix("view", viewMatrix);
  44899. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44900. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  44901. // Fog
  44902. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44903. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  44904. effect.setColor3("vFogColor", this._scene.fogColor);
  44905. }
  44906. // VBOs
  44907. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44908. // Draw order
  44909. engine.setDepthFunctionToLessOrEqual();
  44910. effect.setBool("alphaTest", true);
  44911. engine.setColorWrite(false);
  44912. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44913. engine.setColorWrite(true);
  44914. effect.setBool("alphaTest", false);
  44915. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44916. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44917. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44918. };
  44919. SpriteManager.prototype.dispose = function () {
  44920. if (this._buffer) {
  44921. this._buffer.dispose();
  44922. this._buffer = null;
  44923. }
  44924. if (this._indexBuffer) {
  44925. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44926. this._indexBuffer = null;
  44927. }
  44928. if (this._spriteTexture) {
  44929. this._spriteTexture.dispose();
  44930. this._spriteTexture = null;
  44931. }
  44932. // Remove from scene
  44933. var index = this._scene.spriteManagers.indexOf(this);
  44934. this._scene.spriteManagers.splice(index, 1);
  44935. // Callback
  44936. this.onDisposeObservable.notifyObservers(this);
  44937. this.onDisposeObservable.clear();
  44938. };
  44939. return SpriteManager;
  44940. }());
  44941. BABYLON.SpriteManager = SpriteManager;
  44942. })(BABYLON || (BABYLON = {}));
  44943. //# sourceMappingURL=babylon.spriteManager.js.map
  44944. var BABYLON;
  44945. (function (BABYLON) {
  44946. var Sprite = /** @class */ (function () {
  44947. function Sprite(name, manager) {
  44948. this.name = name;
  44949. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44950. this.width = 1.0;
  44951. this.height = 1.0;
  44952. this.angle = 0;
  44953. this.cellIndex = 0;
  44954. this.invertU = 0;
  44955. this.invertV = 0;
  44956. this.animations = new Array();
  44957. this.isPickable = false;
  44958. this._animationStarted = false;
  44959. this._loopAnimation = false;
  44960. this._fromIndex = 0;
  44961. this._toIndex = 0;
  44962. this._delay = 0;
  44963. this._direction = 1;
  44964. this._time = 0;
  44965. this._manager = manager;
  44966. this._manager.sprites.push(this);
  44967. this.position = BABYLON.Vector3.Zero();
  44968. }
  44969. Object.defineProperty(Sprite.prototype, "size", {
  44970. get: function () {
  44971. return this.width;
  44972. },
  44973. set: function (value) {
  44974. this.width = value;
  44975. this.height = value;
  44976. },
  44977. enumerable: true,
  44978. configurable: true
  44979. });
  44980. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  44981. this._fromIndex = from;
  44982. this._toIndex = to;
  44983. this._loopAnimation = loop;
  44984. this._delay = delay;
  44985. this._animationStarted = true;
  44986. this._direction = from < to ? 1 : -1;
  44987. this.cellIndex = from;
  44988. this._time = 0;
  44989. this._onAnimationEnd = onAnimationEnd;
  44990. };
  44991. Sprite.prototype.stopAnimation = function () {
  44992. this._animationStarted = false;
  44993. };
  44994. Sprite.prototype._animate = function (deltaTime) {
  44995. if (!this._animationStarted)
  44996. return;
  44997. this._time += deltaTime;
  44998. if (this._time > this._delay) {
  44999. this._time = this._time % this._delay;
  45000. this.cellIndex += this._direction;
  45001. if (this.cellIndex > this._toIndex) {
  45002. if (this._loopAnimation) {
  45003. this.cellIndex = this._fromIndex;
  45004. }
  45005. else {
  45006. this.cellIndex = this._toIndex;
  45007. this._animationStarted = false;
  45008. if (this._onAnimationEnd) {
  45009. this._onAnimationEnd();
  45010. }
  45011. if (this.disposeWhenFinishedAnimating) {
  45012. this.dispose();
  45013. }
  45014. }
  45015. }
  45016. }
  45017. };
  45018. Sprite.prototype.dispose = function () {
  45019. for (var i = 0; i < this._manager.sprites.length; i++) {
  45020. if (this._manager.sprites[i] == this) {
  45021. this._manager.sprites.splice(i, 1);
  45022. }
  45023. }
  45024. };
  45025. return Sprite;
  45026. }());
  45027. BABYLON.Sprite = Sprite;
  45028. })(BABYLON || (BABYLON = {}));
  45029. //# sourceMappingURL=babylon.sprite.js.map
  45030. var BABYLON;
  45031. (function (BABYLON) {
  45032. var IntersectionInfo = /** @class */ (function () {
  45033. function IntersectionInfo(bu, bv, distance) {
  45034. this.bu = bu;
  45035. this.bv = bv;
  45036. this.distance = distance;
  45037. this.faceId = 0;
  45038. this.subMeshId = 0;
  45039. }
  45040. return IntersectionInfo;
  45041. }());
  45042. BABYLON.IntersectionInfo = IntersectionInfo;
  45043. var PickingInfo = /** @class */ (function () {
  45044. function PickingInfo() {
  45045. this.hit = false;
  45046. this.distance = 0;
  45047. this.pickedPoint = null;
  45048. this.pickedMesh = null;
  45049. this.bu = 0;
  45050. this.bv = 0;
  45051. this.faceId = -1;
  45052. this.subMeshId = 0;
  45053. this.pickedSprite = null;
  45054. }
  45055. // Methods
  45056. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  45057. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  45058. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  45059. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45060. return null;
  45061. }
  45062. var indices = this.pickedMesh.getIndices();
  45063. if (!indices) {
  45064. return null;
  45065. }
  45066. var result;
  45067. if (useVerticesNormals) {
  45068. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45069. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  45070. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  45071. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  45072. normal0 = normal0.scale(this.bu);
  45073. normal1 = normal1.scale(this.bv);
  45074. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  45075. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  45076. }
  45077. else {
  45078. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45079. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  45080. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  45081. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  45082. var p1p2 = vertex1.subtract(vertex2);
  45083. var p3p2 = vertex3.subtract(vertex2);
  45084. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  45085. }
  45086. if (useWorldCoordinates) {
  45087. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  45088. }
  45089. return BABYLON.Vector3.Normalize(result);
  45090. };
  45091. PickingInfo.prototype.getTextureCoordinates = function () {
  45092. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45093. return null;
  45094. }
  45095. var indices = this.pickedMesh.getIndices();
  45096. if (!indices) {
  45097. return null;
  45098. }
  45099. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45100. if (!uvs) {
  45101. return null;
  45102. }
  45103. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  45104. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  45105. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  45106. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  45107. uv1 = uv1.scale(this.bu);
  45108. uv2 = uv2.scale(this.bv);
  45109. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  45110. };
  45111. return PickingInfo;
  45112. }());
  45113. BABYLON.PickingInfo = PickingInfo;
  45114. })(BABYLON || (BABYLON = {}));
  45115. //# sourceMappingURL=babylon.pickingInfo.js.map
  45116. var BABYLON;
  45117. (function (BABYLON) {
  45118. var Ray = /** @class */ (function () {
  45119. function Ray(origin, direction, length) {
  45120. if (length === void 0) { length = Number.MAX_VALUE; }
  45121. this.origin = origin;
  45122. this.direction = direction;
  45123. this.length = length;
  45124. }
  45125. // Methods
  45126. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  45127. var d = 0.0;
  45128. var maxValue = Number.MAX_VALUE;
  45129. var inv;
  45130. var min;
  45131. var max;
  45132. var temp;
  45133. if (Math.abs(this.direction.x) < 0.0000001) {
  45134. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  45135. return false;
  45136. }
  45137. }
  45138. else {
  45139. inv = 1.0 / this.direction.x;
  45140. min = (minimum.x - this.origin.x) * inv;
  45141. max = (maximum.x - this.origin.x) * inv;
  45142. if (max === -Infinity) {
  45143. max = Infinity;
  45144. }
  45145. if (min > max) {
  45146. temp = min;
  45147. min = max;
  45148. max = temp;
  45149. }
  45150. d = Math.max(min, d);
  45151. maxValue = Math.min(max, maxValue);
  45152. if (d > maxValue) {
  45153. return false;
  45154. }
  45155. }
  45156. if (Math.abs(this.direction.y) < 0.0000001) {
  45157. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  45158. return false;
  45159. }
  45160. }
  45161. else {
  45162. inv = 1.0 / this.direction.y;
  45163. min = (minimum.y - this.origin.y) * inv;
  45164. max = (maximum.y - this.origin.y) * inv;
  45165. if (max === -Infinity) {
  45166. max = Infinity;
  45167. }
  45168. if (min > max) {
  45169. temp = min;
  45170. min = max;
  45171. max = temp;
  45172. }
  45173. d = Math.max(min, d);
  45174. maxValue = Math.min(max, maxValue);
  45175. if (d > maxValue) {
  45176. return false;
  45177. }
  45178. }
  45179. if (Math.abs(this.direction.z) < 0.0000001) {
  45180. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  45181. return false;
  45182. }
  45183. }
  45184. else {
  45185. inv = 1.0 / this.direction.z;
  45186. min = (minimum.z - this.origin.z) * inv;
  45187. max = (maximum.z - this.origin.z) * inv;
  45188. if (max === -Infinity) {
  45189. max = Infinity;
  45190. }
  45191. if (min > max) {
  45192. temp = min;
  45193. min = max;
  45194. max = temp;
  45195. }
  45196. d = Math.max(min, d);
  45197. maxValue = Math.min(max, maxValue);
  45198. if (d > maxValue) {
  45199. return false;
  45200. }
  45201. }
  45202. return true;
  45203. };
  45204. Ray.prototype.intersectsBox = function (box) {
  45205. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  45206. };
  45207. Ray.prototype.intersectsSphere = function (sphere) {
  45208. var x = sphere.center.x - this.origin.x;
  45209. var y = sphere.center.y - this.origin.y;
  45210. var z = sphere.center.z - this.origin.z;
  45211. var pyth = (x * x) + (y * y) + (z * z);
  45212. var rr = sphere.radius * sphere.radius;
  45213. if (pyth <= rr) {
  45214. return true;
  45215. }
  45216. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  45217. if (dot < 0.0) {
  45218. return false;
  45219. }
  45220. var temp = pyth - (dot * dot);
  45221. return temp <= rr;
  45222. };
  45223. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  45224. if (!this._edge1) {
  45225. this._edge1 = BABYLON.Vector3.Zero();
  45226. this._edge2 = BABYLON.Vector3.Zero();
  45227. this._pvec = BABYLON.Vector3.Zero();
  45228. this._tvec = BABYLON.Vector3.Zero();
  45229. this._qvec = BABYLON.Vector3.Zero();
  45230. }
  45231. vertex1.subtractToRef(vertex0, this._edge1);
  45232. vertex2.subtractToRef(vertex0, this._edge2);
  45233. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  45234. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  45235. if (det === 0) {
  45236. return null;
  45237. }
  45238. var invdet = 1 / det;
  45239. this.origin.subtractToRef(vertex0, this._tvec);
  45240. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  45241. if (bu < 0 || bu > 1.0) {
  45242. return null;
  45243. }
  45244. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  45245. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  45246. if (bv < 0 || bu + bv > 1.0) {
  45247. return null;
  45248. }
  45249. //check if the distance is longer than the predefined length.
  45250. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  45251. if (distance > this.length) {
  45252. return null;
  45253. }
  45254. return new BABYLON.IntersectionInfo(bu, bv, distance);
  45255. };
  45256. Ray.prototype.intersectsPlane = function (plane) {
  45257. var distance;
  45258. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  45259. if (Math.abs(result1) < 9.99999997475243E-07) {
  45260. return null;
  45261. }
  45262. else {
  45263. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  45264. distance = (-plane.d - result2) / result1;
  45265. if (distance < 0.0) {
  45266. if (distance < -9.99999997475243E-07) {
  45267. return null;
  45268. }
  45269. else {
  45270. return 0;
  45271. }
  45272. }
  45273. return distance;
  45274. }
  45275. };
  45276. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  45277. var tm = BABYLON.Tmp.Matrix[0];
  45278. mesh.getWorldMatrix().invertToRef(tm);
  45279. if (this._tmpRay) {
  45280. Ray.TransformToRef(this, tm, this._tmpRay);
  45281. }
  45282. else {
  45283. this._tmpRay = Ray.Transform(this, tm);
  45284. }
  45285. return mesh.intersects(this._tmpRay, fastCheck);
  45286. };
  45287. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  45288. if (results) {
  45289. results.length = 0;
  45290. }
  45291. else {
  45292. results = [];
  45293. }
  45294. for (var i = 0; i < meshes.length; i++) {
  45295. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  45296. if (pickInfo.hit) {
  45297. results.push(pickInfo);
  45298. }
  45299. }
  45300. results.sort(this._comparePickingInfo);
  45301. return results;
  45302. };
  45303. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  45304. if (pickingInfoA.distance < pickingInfoB.distance) {
  45305. return -1;
  45306. }
  45307. else if (pickingInfoA.distance > pickingInfoB.distance) {
  45308. return 1;
  45309. }
  45310. else {
  45311. return 0;
  45312. }
  45313. };
  45314. /**
  45315. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  45316. * @param sega the first point of the segment to test the intersection against
  45317. * @param segb the second point of the segment to test the intersection against
  45318. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  45319. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  45320. */
  45321. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  45322. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  45323. var u = segb.subtract(sega);
  45324. var v = rsegb.subtract(this.origin);
  45325. var w = sega.subtract(this.origin);
  45326. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  45327. var b = BABYLON.Vector3.Dot(u, v);
  45328. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  45329. var d = BABYLON.Vector3.Dot(u, w);
  45330. var e = BABYLON.Vector3.Dot(v, w);
  45331. var D = a * c - b * b; // always >= 0
  45332. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  45333. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  45334. // compute the line parameters of the two closest points
  45335. if (D < Ray.smallnum) {
  45336. sN = 0.0; // force using point P0 on segment S1
  45337. sD = 1.0; // to prevent possible division by 0.0 later
  45338. tN = e;
  45339. tD = c;
  45340. }
  45341. else {
  45342. sN = (b * e - c * d);
  45343. tN = (a * e - b * d);
  45344. if (sN < 0.0) {
  45345. sN = 0.0;
  45346. tN = e;
  45347. tD = c;
  45348. }
  45349. else if (sN > sD) {
  45350. sN = sD;
  45351. tN = e + b;
  45352. tD = c;
  45353. }
  45354. }
  45355. if (tN < 0.0) {
  45356. tN = 0.0;
  45357. // recompute sc for this edge
  45358. if (-d < 0.0) {
  45359. sN = 0.0;
  45360. }
  45361. else if (-d > a)
  45362. sN = sD;
  45363. else {
  45364. sN = -d;
  45365. sD = a;
  45366. }
  45367. }
  45368. else if (tN > tD) {
  45369. tN = tD;
  45370. // recompute sc for this edge
  45371. if ((-d + b) < 0.0) {
  45372. sN = 0;
  45373. }
  45374. else if ((-d + b) > a) {
  45375. sN = sD;
  45376. }
  45377. else {
  45378. sN = (-d + b);
  45379. sD = a;
  45380. }
  45381. }
  45382. // finally do the division to get sc and tc
  45383. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  45384. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  45385. // get the difference of the two closest points
  45386. var qtc = v.multiplyByFloats(tc, tc, tc);
  45387. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  45388. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  45389. if (isIntersected) {
  45390. return qtc.length();
  45391. }
  45392. return -1;
  45393. };
  45394. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  45395. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  45396. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  45397. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  45398. this.direction.normalize();
  45399. return this;
  45400. };
  45401. // Statics
  45402. Ray.Zero = function () {
  45403. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  45404. };
  45405. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  45406. var result = Ray.Zero();
  45407. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  45408. };
  45409. /**
  45410. * 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
  45411. * transformed to the given world matrix.
  45412. * @param origin The origin point
  45413. * @param end The end point
  45414. * @param world a matrix to transform the ray to. Default is the identity matrix.
  45415. */
  45416. Ray.CreateNewFromTo = function (origin, end, world) {
  45417. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  45418. var direction = end.subtract(origin);
  45419. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  45420. direction.normalize();
  45421. return Ray.Transform(new Ray(origin, direction, length), world);
  45422. };
  45423. Ray.Transform = function (ray, matrix) {
  45424. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  45425. Ray.TransformToRef(ray, matrix, result);
  45426. return result;
  45427. };
  45428. Ray.TransformToRef = function (ray, matrix, result) {
  45429. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  45430. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  45431. result.length = ray.length;
  45432. var dir = result.direction;
  45433. var len = dir.length();
  45434. if (!(len === 0 || len === 1)) {
  45435. var num = 1.0 / len;
  45436. dir.x *= num;
  45437. dir.y *= num;
  45438. dir.z *= num;
  45439. result.length *= len;
  45440. }
  45441. };
  45442. Ray.smallnum = 0.00000001;
  45443. Ray.rayl = 10e8;
  45444. return Ray;
  45445. }());
  45446. BABYLON.Ray = Ray;
  45447. })(BABYLON || (BABYLON = {}));
  45448. //# sourceMappingURL=babylon.ray.js.map
  45449. var BABYLON;
  45450. (function (BABYLON) {
  45451. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  45452. if (boxMin.x > sphereCenter.x + sphereRadius)
  45453. return false;
  45454. if (sphereCenter.x - sphereRadius > boxMax.x)
  45455. return false;
  45456. if (boxMin.y > sphereCenter.y + sphereRadius)
  45457. return false;
  45458. if (sphereCenter.y - sphereRadius > boxMax.y)
  45459. return false;
  45460. if (boxMin.z > sphereCenter.z + sphereRadius)
  45461. return false;
  45462. if (sphereCenter.z - sphereRadius > boxMax.z)
  45463. return false;
  45464. return true;
  45465. };
  45466. var getLowestRoot = (function () {
  45467. var result = { root: 0, found: false };
  45468. return function (a, b, c, maxR) {
  45469. result.root = 0;
  45470. result.found = false;
  45471. var determinant = b * b - 4.0 * a * c;
  45472. if (determinant < 0)
  45473. return result;
  45474. var sqrtD = Math.sqrt(determinant);
  45475. var r1 = (-b - sqrtD) / (2.0 * a);
  45476. var r2 = (-b + sqrtD) / (2.0 * a);
  45477. if (r1 > r2) {
  45478. var temp = r2;
  45479. r2 = r1;
  45480. r1 = temp;
  45481. }
  45482. if (r1 > 0 && r1 < maxR) {
  45483. result.root = r1;
  45484. result.found = true;
  45485. return result;
  45486. }
  45487. if (r2 > 0 && r2 < maxR) {
  45488. result.root = r2;
  45489. result.found = true;
  45490. return result;
  45491. }
  45492. return result;
  45493. };
  45494. })();
  45495. var Collider = /** @class */ (function () {
  45496. function Collider() {
  45497. this._collisionPoint = BABYLON.Vector3.Zero();
  45498. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  45499. this._tempVector = BABYLON.Vector3.Zero();
  45500. this._tempVector2 = BABYLON.Vector3.Zero();
  45501. this._tempVector3 = BABYLON.Vector3.Zero();
  45502. this._tempVector4 = BABYLON.Vector3.Zero();
  45503. this._edge = BABYLON.Vector3.Zero();
  45504. this._baseToVertex = BABYLON.Vector3.Zero();
  45505. this._destinationPoint = BABYLON.Vector3.Zero();
  45506. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  45507. this._displacementVector = BABYLON.Vector3.Zero();
  45508. this._radius = BABYLON.Vector3.One();
  45509. this._retry = 0;
  45510. this._basePointWorld = BABYLON.Vector3.Zero();
  45511. this._velocityWorld = BABYLON.Vector3.Zero();
  45512. this._normalizedVelocity = BABYLON.Vector3.Zero();
  45513. this._collisionMask = -1;
  45514. }
  45515. Object.defineProperty(Collider.prototype, "collisionMask", {
  45516. get: function () {
  45517. return this._collisionMask;
  45518. },
  45519. set: function (mask) {
  45520. this._collisionMask = !isNaN(mask) ? mask : -1;
  45521. },
  45522. enumerable: true,
  45523. configurable: true
  45524. });
  45525. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  45526. /**
  45527. * Gets the plane normal used to compute the sliding response (in local space)
  45528. */
  45529. get: function () {
  45530. return this._slidePlaneNormal;
  45531. },
  45532. enumerable: true,
  45533. configurable: true
  45534. });
  45535. // Methods
  45536. Collider.prototype._initialize = function (source, dir, e) {
  45537. this._velocity = dir;
  45538. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  45539. this._basePoint = source;
  45540. source.multiplyToRef(this._radius, this._basePointWorld);
  45541. dir.multiplyToRef(this._radius, this._velocityWorld);
  45542. this._velocityWorldLength = this._velocityWorld.length();
  45543. this._epsilon = e;
  45544. this.collisionFound = false;
  45545. };
  45546. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  45547. pa.subtractToRef(point, this._tempVector);
  45548. pb.subtractToRef(point, this._tempVector2);
  45549. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  45550. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45551. if (d < 0)
  45552. return false;
  45553. pc.subtractToRef(point, this._tempVector3);
  45554. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  45555. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45556. if (d < 0)
  45557. return false;
  45558. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  45559. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45560. return d >= 0;
  45561. };
  45562. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  45563. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  45564. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  45565. if (distance > this._velocityWorldLength + max + sphereRadius) {
  45566. return false;
  45567. }
  45568. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  45569. return false;
  45570. return true;
  45571. };
  45572. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  45573. var t0;
  45574. var embeddedInPlane = false;
  45575. //defensive programming, actually not needed.
  45576. if (!trianglePlaneArray) {
  45577. trianglePlaneArray = [];
  45578. }
  45579. if (!trianglePlaneArray[faceIndex]) {
  45580. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  45581. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  45582. }
  45583. var trianglePlane = trianglePlaneArray[faceIndex];
  45584. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  45585. return;
  45586. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  45587. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  45588. if (normalDotVelocity == 0) {
  45589. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  45590. return;
  45591. embeddedInPlane = true;
  45592. t0 = 0;
  45593. }
  45594. else {
  45595. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45596. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45597. if (t0 > t1) {
  45598. var temp = t1;
  45599. t1 = t0;
  45600. t0 = temp;
  45601. }
  45602. if (t0 > 1.0 || t1 < 0.0)
  45603. return;
  45604. if (t0 < 0)
  45605. t0 = 0;
  45606. if (t0 > 1.0)
  45607. t0 = 1.0;
  45608. }
  45609. this._collisionPoint.copyFromFloats(0, 0, 0);
  45610. var found = false;
  45611. var t = 1.0;
  45612. if (!embeddedInPlane) {
  45613. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  45614. this._velocity.scaleToRef(t0, this._tempVector);
  45615. this._planeIntersectionPoint.addInPlace(this._tempVector);
  45616. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  45617. found = true;
  45618. t = t0;
  45619. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  45620. }
  45621. }
  45622. if (!found) {
  45623. var velocitySquaredLength = this._velocity.lengthSquared();
  45624. var a = velocitySquaredLength;
  45625. this._basePoint.subtractToRef(p1, this._tempVector);
  45626. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45627. var c = this._tempVector.lengthSquared() - 1.0;
  45628. var lowestRoot = getLowestRoot(a, b, c, t);
  45629. if (lowestRoot.found) {
  45630. t = lowestRoot.root;
  45631. found = true;
  45632. this._collisionPoint.copyFrom(p1);
  45633. }
  45634. this._basePoint.subtractToRef(p2, this._tempVector);
  45635. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45636. c = this._tempVector.lengthSquared() - 1.0;
  45637. lowestRoot = getLowestRoot(a, b, c, t);
  45638. if (lowestRoot.found) {
  45639. t = lowestRoot.root;
  45640. found = true;
  45641. this._collisionPoint.copyFrom(p2);
  45642. }
  45643. this._basePoint.subtractToRef(p3, this._tempVector);
  45644. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45645. c = this._tempVector.lengthSquared() - 1.0;
  45646. lowestRoot = getLowestRoot(a, b, c, t);
  45647. if (lowestRoot.found) {
  45648. t = lowestRoot.root;
  45649. found = true;
  45650. this._collisionPoint.copyFrom(p3);
  45651. }
  45652. p2.subtractToRef(p1, this._edge);
  45653. p1.subtractToRef(this._basePoint, this._baseToVertex);
  45654. var edgeSquaredLength = this._edge.lengthSquared();
  45655. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45656. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45657. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45658. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45659. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45660. lowestRoot = getLowestRoot(a, b, c, t);
  45661. if (lowestRoot.found) {
  45662. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45663. if (f >= 0.0 && f <= 1.0) {
  45664. t = lowestRoot.root;
  45665. found = true;
  45666. this._edge.scaleInPlace(f);
  45667. p1.addToRef(this._edge, this._collisionPoint);
  45668. }
  45669. }
  45670. p3.subtractToRef(p2, this._edge);
  45671. p2.subtractToRef(this._basePoint, this._baseToVertex);
  45672. edgeSquaredLength = this._edge.lengthSquared();
  45673. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45674. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45675. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45676. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45677. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45678. lowestRoot = getLowestRoot(a, b, c, t);
  45679. if (lowestRoot.found) {
  45680. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45681. if (f >= 0.0 && f <= 1.0) {
  45682. t = lowestRoot.root;
  45683. found = true;
  45684. this._edge.scaleInPlace(f);
  45685. p2.addToRef(this._edge, this._collisionPoint);
  45686. }
  45687. }
  45688. p1.subtractToRef(p3, this._edge);
  45689. p3.subtractToRef(this._basePoint, this._baseToVertex);
  45690. edgeSquaredLength = this._edge.lengthSquared();
  45691. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45692. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45693. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45694. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45695. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45696. lowestRoot = getLowestRoot(a, b, c, t);
  45697. if (lowestRoot.found) {
  45698. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45699. if (f >= 0.0 && f <= 1.0) {
  45700. t = lowestRoot.root;
  45701. found = true;
  45702. this._edge.scaleInPlace(f);
  45703. p3.addToRef(this._edge, this._collisionPoint);
  45704. }
  45705. }
  45706. }
  45707. if (found) {
  45708. var distToCollision = t * this._velocity.length();
  45709. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  45710. if (!this.intersectionPoint) {
  45711. this.intersectionPoint = this._collisionPoint.clone();
  45712. }
  45713. else {
  45714. this.intersectionPoint.copyFrom(this._collisionPoint);
  45715. }
  45716. this._nearestDistance = distToCollision;
  45717. this.collisionFound = true;
  45718. }
  45719. }
  45720. };
  45721. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  45722. for (var i = indexStart; i < indexEnd; i += 3) {
  45723. var p1 = pts[indices[i] - decal];
  45724. var p2 = pts[indices[i + 1] - decal];
  45725. var p3 = pts[indices[i + 2] - decal];
  45726. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  45727. }
  45728. };
  45729. Collider.prototype._getResponse = function (pos, vel) {
  45730. pos.addToRef(vel, this._destinationPoint);
  45731. vel.scaleInPlace((this._nearestDistance / vel.length()));
  45732. this._basePoint.addToRef(vel, pos);
  45733. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  45734. this._slidePlaneNormal.normalize();
  45735. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  45736. pos.addInPlace(this._displacementVector);
  45737. this.intersectionPoint.addInPlace(this._displacementVector);
  45738. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  45739. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  45740. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  45741. };
  45742. return Collider;
  45743. }());
  45744. BABYLON.Collider = Collider;
  45745. })(BABYLON || (BABYLON = {}));
  45746. //# sourceMappingURL=babylon.collider.js.map
  45747. var BABYLON;
  45748. (function (BABYLON) {
  45749. //WebWorker code will be inserted to this variable.
  45750. BABYLON.CollisionWorker = "";
  45751. var WorkerTaskType;
  45752. (function (WorkerTaskType) {
  45753. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  45754. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  45755. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  45756. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  45757. var WorkerReplyType;
  45758. (function (WorkerReplyType) {
  45759. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  45760. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  45761. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  45762. var CollisionCoordinatorWorker = /** @class */ (function () {
  45763. function CollisionCoordinatorWorker() {
  45764. var _this = this;
  45765. this._scaledPosition = BABYLON.Vector3.Zero();
  45766. this._scaledVelocity = BABYLON.Vector3.Zero();
  45767. this.onMeshUpdated = function (transformNode) {
  45768. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  45769. };
  45770. this.onGeometryUpdated = function (geometry) {
  45771. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  45772. };
  45773. this._afterRender = function () {
  45774. if (!_this._init)
  45775. return;
  45776. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  45777. return;
  45778. }
  45779. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  45780. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  45781. if (_this._runningUpdated > 4) {
  45782. return;
  45783. }
  45784. ++_this._runningUpdated;
  45785. var payload = {
  45786. updatedMeshes: _this._addUpdateMeshesList,
  45787. updatedGeometries: _this._addUpdateGeometriesList,
  45788. removedGeometries: _this._toRemoveGeometryArray,
  45789. removedMeshes: _this._toRemoveMeshesArray
  45790. };
  45791. var message = {
  45792. payload: payload,
  45793. taskType: WorkerTaskType.UPDATE
  45794. };
  45795. var serializable = [];
  45796. for (var id in payload.updatedGeometries) {
  45797. if (payload.updatedGeometries.hasOwnProperty(id)) {
  45798. //prepare transferables
  45799. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  45800. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  45801. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  45802. }
  45803. }
  45804. _this._worker.postMessage(message, serializable);
  45805. _this._addUpdateMeshesList = {};
  45806. _this._addUpdateGeometriesList = {};
  45807. _this._toRemoveGeometryArray = [];
  45808. _this._toRemoveMeshesArray = [];
  45809. };
  45810. this._onMessageFromWorker = function (e) {
  45811. var returnData = e.data;
  45812. if (returnData.error != WorkerReplyType.SUCCESS) {
  45813. //TODO what errors can be returned from the worker?
  45814. BABYLON.Tools.Warn("error returned from worker!");
  45815. return;
  45816. }
  45817. switch (returnData.taskType) {
  45818. case WorkerTaskType.INIT:
  45819. _this._init = true;
  45820. //Update the worked with ALL of the scene's current state
  45821. _this._scene.meshes.forEach(function (mesh) {
  45822. _this.onMeshAdded(mesh);
  45823. });
  45824. _this._scene.getGeometries().forEach(function (geometry) {
  45825. _this.onGeometryAdded(geometry);
  45826. });
  45827. break;
  45828. case WorkerTaskType.UPDATE:
  45829. _this._runningUpdated--;
  45830. break;
  45831. case WorkerTaskType.COLLIDE:
  45832. var returnPayload = returnData.payload;
  45833. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  45834. return;
  45835. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  45836. if (callback) {
  45837. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  45838. if (mesh) {
  45839. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  45840. }
  45841. }
  45842. //cleanup
  45843. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  45844. break;
  45845. }
  45846. };
  45847. this._collisionsCallbackArray = [];
  45848. this._init = false;
  45849. this._runningUpdated = 0;
  45850. this._addUpdateMeshesList = {};
  45851. this._addUpdateGeometriesList = {};
  45852. this._toRemoveGeometryArray = [];
  45853. this._toRemoveMeshesArray = [];
  45854. }
  45855. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45856. if (!this._init)
  45857. return;
  45858. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  45859. return;
  45860. position.divideToRef(collider._radius, this._scaledPosition);
  45861. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45862. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  45863. var payload = {
  45864. collider: {
  45865. position: this._scaledPosition.asArray(),
  45866. velocity: this._scaledVelocity.asArray(),
  45867. radius: collider._radius.asArray()
  45868. },
  45869. collisionId: collisionIndex,
  45870. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  45871. maximumRetry: maximumRetry
  45872. };
  45873. var message = {
  45874. payload: payload,
  45875. taskType: WorkerTaskType.COLLIDE
  45876. };
  45877. this._worker.postMessage(message);
  45878. };
  45879. CollisionCoordinatorWorker.prototype.init = function (scene) {
  45880. this._scene = scene;
  45881. this._scene.registerAfterRender(this._afterRender);
  45882. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  45883. this._worker = new Worker(workerUrl);
  45884. this._worker.onmessage = this._onMessageFromWorker;
  45885. var message = {
  45886. payload: {},
  45887. taskType: WorkerTaskType.INIT
  45888. };
  45889. this._worker.postMessage(message);
  45890. };
  45891. CollisionCoordinatorWorker.prototype.destroy = function () {
  45892. this._scene.unregisterAfterRender(this._afterRender);
  45893. this._worker.terminate();
  45894. };
  45895. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  45896. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  45897. this.onMeshUpdated(mesh);
  45898. };
  45899. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  45900. this._toRemoveMeshesArray.push(mesh.uniqueId);
  45901. };
  45902. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  45903. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  45904. geometry.onGeometryUpdated = this.onGeometryUpdated;
  45905. this.onGeometryUpdated(geometry);
  45906. };
  45907. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  45908. this._toRemoveGeometryArray.push(geometry.id);
  45909. };
  45910. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  45911. var submeshes = [];
  45912. if (mesh.subMeshes) {
  45913. submeshes = mesh.subMeshes.map(function (sm, idx) {
  45914. var boundingInfo = sm.getBoundingInfo();
  45915. return {
  45916. position: idx,
  45917. verticesStart: sm.verticesStart,
  45918. verticesCount: sm.verticesCount,
  45919. indexStart: sm.indexStart,
  45920. indexCount: sm.indexCount,
  45921. hasMaterial: !!sm.getMaterial(),
  45922. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45923. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45924. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45925. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  45926. };
  45927. });
  45928. }
  45929. var geometryId = null;
  45930. if (mesh instanceof BABYLON.Mesh) {
  45931. var geometry = mesh.geometry;
  45932. geometryId = geometry ? geometry.id : null;
  45933. }
  45934. else if (mesh instanceof BABYLON.InstancedMesh) {
  45935. var geometry = mesh.sourceMesh.geometry;
  45936. geometryId = geometry ? geometry.id : null;
  45937. }
  45938. var boundingInfo = mesh.getBoundingInfo();
  45939. return {
  45940. uniqueId: mesh.uniqueId,
  45941. id: mesh.id,
  45942. name: mesh.name,
  45943. geometryId: geometryId,
  45944. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45945. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45946. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45947. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  45948. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  45949. subMeshes: submeshes,
  45950. checkCollisions: mesh.checkCollisions
  45951. };
  45952. };
  45953. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  45954. return {
  45955. id: geometry.id,
  45956. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  45957. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  45958. indices: new Uint32Array(geometry.getIndices() || []),
  45959. };
  45960. };
  45961. return CollisionCoordinatorWorker;
  45962. }());
  45963. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  45964. var CollisionCoordinatorLegacy = /** @class */ (function () {
  45965. function CollisionCoordinatorLegacy() {
  45966. this._scaledPosition = BABYLON.Vector3.Zero();
  45967. this._scaledVelocity = BABYLON.Vector3.Zero();
  45968. this._finalPosition = BABYLON.Vector3.Zero();
  45969. }
  45970. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45971. position.divideToRef(collider._radius, this._scaledPosition);
  45972. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45973. collider.collidedMesh = null;
  45974. collider._retry = 0;
  45975. collider._initialVelocity = this._scaledVelocity;
  45976. collider._initialPosition = this._scaledPosition;
  45977. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  45978. this._finalPosition.multiplyInPlace(collider._radius);
  45979. //run the callback
  45980. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  45981. };
  45982. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  45983. this._scene = scene;
  45984. };
  45985. CollisionCoordinatorLegacy.prototype.destroy = function () {
  45986. //Legacy need no destruction method.
  45987. };
  45988. //No update in legacy mode
  45989. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  45990. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  45991. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  45992. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  45993. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  45994. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  45995. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  45996. if (excludedMesh === void 0) { excludedMesh = null; }
  45997. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  45998. if (collider._retry >= maximumRetry) {
  45999. finalPosition.copyFrom(position);
  46000. return;
  46001. }
  46002. // Check if this is a mesh else camera or -1
  46003. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  46004. collider._initialize(position, velocity, closeDistance);
  46005. // Check all meshes
  46006. for (var index = 0; index < this._scene.meshes.length; index++) {
  46007. var mesh = this._scene.meshes[index];
  46008. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  46009. mesh._checkCollision(collider);
  46010. }
  46011. }
  46012. if (!collider.collisionFound) {
  46013. position.addToRef(velocity, finalPosition);
  46014. return;
  46015. }
  46016. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  46017. collider._getResponse(position, velocity);
  46018. }
  46019. if (velocity.length() <= closeDistance) {
  46020. finalPosition.copyFrom(position);
  46021. return;
  46022. }
  46023. collider._retry++;
  46024. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  46025. };
  46026. return CollisionCoordinatorLegacy;
  46027. }());
  46028. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  46029. })(BABYLON || (BABYLON = {}));
  46030. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  46031. var BABYLON;
  46032. (function (BABYLON) {
  46033. var Particle = /** @class */ (function () {
  46034. function Particle(particleSystem) {
  46035. this.particleSystem = particleSystem;
  46036. this.position = BABYLON.Vector3.Zero();
  46037. this.direction = BABYLON.Vector3.Zero();
  46038. this.color = new BABYLON.Color4(0, 0, 0, 0);
  46039. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  46040. this.lifeTime = 1.0;
  46041. this.age = 0;
  46042. this.size = 0;
  46043. this.angle = 0;
  46044. this.angularSpeed = 0;
  46045. this._currentFrameCounter = 0;
  46046. this.cellIndex = 0;
  46047. if (!this.particleSystem.isAnimationSheetEnabled) {
  46048. return;
  46049. }
  46050. this.cellIndex = this.particleSystem.startSpriteCellID;
  46051. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  46052. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  46053. }
  46054. else {
  46055. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  46056. }
  46057. }
  46058. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  46059. // (ageOffset / scaledUpdateSpeed) / available cells
  46060. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  46061. this._currentFrameCounter += scaledUpdateSpeed;
  46062. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  46063. this._currentFrameCounter = 0;
  46064. this.cellIndex++;
  46065. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  46066. this.cellIndex = this.particleSystem.endSpriteCellID;
  46067. }
  46068. }
  46069. };
  46070. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  46071. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  46072. this.cellIndex++;
  46073. this._currentFrameCounter = 0;
  46074. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  46075. if (this.particleSystem.spriteCellLoop) {
  46076. this.cellIndex = this.particleSystem.startSpriteCellID;
  46077. }
  46078. else {
  46079. this.cellIndex = this.particleSystem.endSpriteCellID;
  46080. }
  46081. }
  46082. }
  46083. else {
  46084. this._currentFrameCounter++;
  46085. }
  46086. };
  46087. Particle.prototype.copyTo = function (other) {
  46088. other.position.copyFrom(this.position);
  46089. other.direction.copyFrom(this.direction);
  46090. other.color.copyFrom(this.color);
  46091. other.colorStep.copyFrom(this.colorStep);
  46092. other.lifeTime = this.lifeTime;
  46093. other.age = this.age;
  46094. other.size = this.size;
  46095. other.angle = this.angle;
  46096. other.angularSpeed = this.angularSpeed;
  46097. other.particleSystem = this.particleSystem;
  46098. other.cellIndex = this.cellIndex;
  46099. };
  46100. return Particle;
  46101. }());
  46102. BABYLON.Particle = Particle;
  46103. })(BABYLON || (BABYLON = {}));
  46104. //# sourceMappingURL=babylon.particle.js.map
  46105. var BABYLON;
  46106. (function (BABYLON) {
  46107. var ParticleSystem = /** @class */ (function () {
  46108. // end of sheet animation
  46109. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  46110. if (customEffect === void 0) { customEffect = null; }
  46111. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  46112. if (epsilon === void 0) { epsilon = 0.01; }
  46113. var _this = this;
  46114. this.name = name;
  46115. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  46116. // Members
  46117. this.animations = [];
  46118. this.renderingGroupId = 0;
  46119. this.emitter = null;
  46120. this.emitRate = 10;
  46121. this.manualEmitCount = -1;
  46122. this.updateSpeed = 0.01;
  46123. this.targetStopDuration = 0;
  46124. this.disposeOnStop = false;
  46125. this.minEmitPower = 1;
  46126. this.maxEmitPower = 1;
  46127. this.minLifeTime = 1;
  46128. this.maxLifeTime = 1;
  46129. this.minSize = 1;
  46130. this.maxSize = 1;
  46131. this.minAngularSpeed = 0;
  46132. this.maxAngularSpeed = 0;
  46133. this.layerMask = 0x0FFFFFFF;
  46134. this.customShader = null;
  46135. this.preventAutoStart = false;
  46136. /**
  46137. * An event triggered when the system is disposed.
  46138. * @type {BABYLON.Observable}
  46139. */
  46140. this.onDisposeObservable = new BABYLON.Observable();
  46141. this.onAnimationEnd = null;
  46142. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  46143. this.forceDepthWrite = false;
  46144. this.gravity = BABYLON.Vector3.Zero();
  46145. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  46146. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  46147. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  46148. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  46149. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46150. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46151. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  46152. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46153. this.particles = new Array();
  46154. this._stockParticles = new Array();
  46155. this._newPartsExcess = 0;
  46156. this._vertexBuffers = {};
  46157. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  46158. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  46159. this._scaledDirection = BABYLON.Vector3.Zero();
  46160. this._scaledGravity = BABYLON.Vector3.Zero();
  46161. this._currentRenderId = -1;
  46162. this._started = false;
  46163. this._stopped = false;
  46164. this._actualFrame = 0;
  46165. // sheet animation
  46166. this.startSpriteCellID = 0;
  46167. this.endSpriteCellID = 0;
  46168. this.spriteCellLoop = true;
  46169. this.spriteCellChangeSpeed = 0;
  46170. this.spriteCellWidth = 0;
  46171. this.spriteCellHeight = 0;
  46172. this._vertexBufferSize = 11;
  46173. this.appendParticleVertexes = null;
  46174. this.id = name;
  46175. this._capacity = capacity;
  46176. this._epsilon = epsilon;
  46177. if (_isAnimationSheetEnabled) {
  46178. this._vertexBufferSize = 12;
  46179. }
  46180. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46181. this._customEffect = customEffect;
  46182. scene.particleSystems.push(this);
  46183. this._createIndexBuffer();
  46184. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  46185. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  46186. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  46187. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  46188. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  46189. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  46190. if (this._isAnimationSheetEnabled) {
  46191. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  46192. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  46193. }
  46194. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  46195. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  46196. this._vertexBuffers["options"] = options;
  46197. // Default behaviors
  46198. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  46199. this.updateFunction = function (particles) {
  46200. for (var index = 0; index < particles.length; index++) {
  46201. var particle = particles[index];
  46202. particle.age += _this._scaledUpdateSpeed;
  46203. if (particle.age >= particle.lifeTime) {
  46204. _this.recycleParticle(particle);
  46205. index--;
  46206. continue;
  46207. }
  46208. else {
  46209. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  46210. particle.color.addInPlace(_this._scaledColorStep);
  46211. if (particle.color.a < 0)
  46212. particle.color.a = 0;
  46213. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  46214. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  46215. particle.position.addInPlace(_this._scaledDirection);
  46216. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  46217. particle.direction.addInPlace(_this._scaledGravity);
  46218. if (_this._isAnimationSheetEnabled) {
  46219. particle.updateCellIndex(_this._scaledUpdateSpeed);
  46220. }
  46221. }
  46222. }
  46223. };
  46224. }
  46225. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  46226. set: function (callback) {
  46227. if (this._onDisposeObserver) {
  46228. this.onDisposeObservable.remove(this._onDisposeObserver);
  46229. }
  46230. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  46231. },
  46232. enumerable: true,
  46233. configurable: true
  46234. });
  46235. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  46236. get: function () {
  46237. return this._isAnimationSheetEnabled;
  46238. },
  46239. enumerable: true,
  46240. configurable: true
  46241. });
  46242. ParticleSystem.prototype._createIndexBuffer = function () {
  46243. var indices = [];
  46244. var index = 0;
  46245. for (var count = 0; count < this._capacity; count++) {
  46246. indices.push(index);
  46247. indices.push(index + 1);
  46248. indices.push(index + 2);
  46249. indices.push(index);
  46250. indices.push(index + 2);
  46251. indices.push(index + 3);
  46252. index += 4;
  46253. }
  46254. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  46255. };
  46256. ParticleSystem.prototype.recycleParticle = function (particle) {
  46257. var lastParticle = this.particles.pop();
  46258. if (lastParticle !== particle) {
  46259. lastParticle.copyTo(particle);
  46260. this._stockParticles.push(lastParticle);
  46261. }
  46262. };
  46263. ParticleSystem.prototype.getCapacity = function () {
  46264. return this._capacity;
  46265. };
  46266. ParticleSystem.prototype.isAlive = function () {
  46267. return this._alive;
  46268. };
  46269. ParticleSystem.prototype.isStarted = function () {
  46270. return this._started;
  46271. };
  46272. ParticleSystem.prototype.start = function () {
  46273. this._started = true;
  46274. this._stopped = false;
  46275. this._actualFrame = 0;
  46276. };
  46277. ParticleSystem.prototype.stop = function () {
  46278. this._stopped = true;
  46279. };
  46280. // animation sheet
  46281. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  46282. var offset = index * this._vertexBufferSize;
  46283. this._vertexData[offset] = particle.position.x;
  46284. this._vertexData[offset + 1] = particle.position.y;
  46285. this._vertexData[offset + 2] = particle.position.z;
  46286. this._vertexData[offset + 3] = particle.color.r;
  46287. this._vertexData[offset + 4] = particle.color.g;
  46288. this._vertexData[offset + 5] = particle.color.b;
  46289. this._vertexData[offset + 6] = particle.color.a;
  46290. this._vertexData[offset + 7] = particle.angle;
  46291. this._vertexData[offset + 8] = particle.size;
  46292. this._vertexData[offset + 9] = offsetX;
  46293. this._vertexData[offset + 10] = offsetY;
  46294. };
  46295. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  46296. if (offsetX === 0)
  46297. offsetX = this._epsilon;
  46298. else if (offsetX === 1)
  46299. offsetX = 1 - this._epsilon;
  46300. if (offsetY === 0)
  46301. offsetY = this._epsilon;
  46302. else if (offsetY === 1)
  46303. offsetY = 1 - this._epsilon;
  46304. var offset = index * this._vertexBufferSize;
  46305. this._vertexData[offset] = particle.position.x;
  46306. this._vertexData[offset + 1] = particle.position.y;
  46307. this._vertexData[offset + 2] = particle.position.z;
  46308. this._vertexData[offset + 3] = particle.color.r;
  46309. this._vertexData[offset + 4] = particle.color.g;
  46310. this._vertexData[offset + 5] = particle.color.b;
  46311. this._vertexData[offset + 6] = particle.color.a;
  46312. this._vertexData[offset + 7] = particle.angle;
  46313. this._vertexData[offset + 8] = particle.size;
  46314. this._vertexData[offset + 9] = offsetX;
  46315. this._vertexData[offset + 10] = offsetY;
  46316. this._vertexData[offset + 11] = particle.cellIndex;
  46317. };
  46318. ParticleSystem.prototype._update = function (newParticles) {
  46319. // Update current
  46320. this._alive = this.particles.length > 0;
  46321. this.updateFunction(this.particles);
  46322. // Add new ones
  46323. var worldMatrix;
  46324. if (this.emitter.position) {
  46325. var emitterMesh = this.emitter;
  46326. worldMatrix = emitterMesh.getWorldMatrix();
  46327. }
  46328. else {
  46329. var emitterPosition = this.emitter;
  46330. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  46331. }
  46332. var particle;
  46333. for (var index = 0; index < newParticles; index++) {
  46334. if (this.particles.length === this._capacity) {
  46335. break;
  46336. }
  46337. if (this._stockParticles.length !== 0) {
  46338. particle = this._stockParticles.pop();
  46339. particle.age = 0;
  46340. particle.cellIndex = this.startSpriteCellID;
  46341. }
  46342. else {
  46343. particle = new BABYLON.Particle(this);
  46344. }
  46345. this.particles.push(particle);
  46346. var emitPower = ParticleSystem.randomNumber(this.minEmitPower, this.maxEmitPower);
  46347. if (this.startDirectionFunction) {
  46348. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  46349. }
  46350. else {
  46351. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  46352. }
  46353. if (this.startPositionFunction) {
  46354. this.startPositionFunction(worldMatrix, particle.position, particle);
  46355. }
  46356. else {
  46357. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  46358. }
  46359. particle.lifeTime = ParticleSystem.randomNumber(this.minLifeTime, this.maxLifeTime);
  46360. particle.size = ParticleSystem.randomNumber(this.minSize, this.maxSize);
  46361. particle.angularSpeed = ParticleSystem.randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  46362. var step = ParticleSystem.randomNumber(0, 1.0);
  46363. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  46364. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  46365. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  46366. }
  46367. };
  46368. ParticleSystem.prototype._getEffect = function () {
  46369. if (this._customEffect) {
  46370. return this._customEffect;
  46371. }
  46372. ;
  46373. var defines = [];
  46374. if (this._scene.clipPlane) {
  46375. defines.push("#define CLIPPLANE");
  46376. }
  46377. if (this._isAnimationSheetEnabled) {
  46378. defines.push("#define ANIMATESHEET");
  46379. }
  46380. // Effect
  46381. var join = defines.join("\n");
  46382. if (this._cachedDefines !== join) {
  46383. this._cachedDefines = join;
  46384. var attributesNamesOrOptions;
  46385. var effectCreationOption;
  46386. if (this._isAnimationSheetEnabled) {
  46387. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  46388. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  46389. }
  46390. else {
  46391. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  46392. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  46393. }
  46394. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  46395. }
  46396. return this._effect;
  46397. };
  46398. ParticleSystem.prototype.animate = function () {
  46399. if (!this._started)
  46400. return;
  46401. var effect = this._getEffect();
  46402. // Check
  46403. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  46404. return;
  46405. if (this._currentRenderId === this._scene.getRenderId()) {
  46406. return;
  46407. }
  46408. this._currentRenderId = this._scene.getRenderId();
  46409. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  46410. // determine the number of particles we need to create
  46411. var newParticles;
  46412. if (this.manualEmitCount > -1) {
  46413. newParticles = this.manualEmitCount;
  46414. this._newPartsExcess = 0;
  46415. this.manualEmitCount = 0;
  46416. }
  46417. else {
  46418. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  46419. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  46420. }
  46421. if (this._newPartsExcess > 1.0) {
  46422. newParticles += this._newPartsExcess >> 0;
  46423. this._newPartsExcess -= this._newPartsExcess >> 0;
  46424. }
  46425. this._alive = false;
  46426. if (!this._stopped) {
  46427. this._actualFrame += this._scaledUpdateSpeed;
  46428. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  46429. this.stop();
  46430. }
  46431. else {
  46432. newParticles = 0;
  46433. }
  46434. this._update(newParticles);
  46435. // Stopped?
  46436. if (this._stopped) {
  46437. if (!this._alive) {
  46438. this._started = false;
  46439. if (this.onAnimationEnd) {
  46440. this.onAnimationEnd();
  46441. }
  46442. if (this.disposeOnStop) {
  46443. this._scene._toBeDisposed.push(this);
  46444. }
  46445. }
  46446. }
  46447. // Animation sheet
  46448. if (this._isAnimationSheetEnabled) {
  46449. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  46450. }
  46451. else {
  46452. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  46453. }
  46454. // Update VBO
  46455. var offset = 0;
  46456. for (var index = 0; index < this.particles.length; index++) {
  46457. var particle = this.particles[index];
  46458. this.appendParticleVertexes(offset, particle);
  46459. offset += 4;
  46460. }
  46461. if (this._vertexBuffer) {
  46462. this._vertexBuffer.update(this._vertexData);
  46463. }
  46464. };
  46465. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  46466. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  46467. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  46468. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  46469. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  46470. };
  46471. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  46472. this._appendParticleVertex(offset++, particle, 0, 0);
  46473. this._appendParticleVertex(offset++, particle, 1, 0);
  46474. this._appendParticleVertex(offset++, particle, 1, 1);
  46475. this._appendParticleVertex(offset++, particle, 0, 1);
  46476. };
  46477. ParticleSystem.prototype.rebuild = function () {
  46478. this._createIndexBuffer();
  46479. if (this._vertexBuffer) {
  46480. this._vertexBuffer._rebuild();
  46481. }
  46482. };
  46483. ParticleSystem.prototype.render = function () {
  46484. var effect = this._getEffect();
  46485. // Check
  46486. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  46487. return 0;
  46488. var engine = this._scene.getEngine();
  46489. // Render
  46490. engine.enableEffect(effect);
  46491. engine.setState(false);
  46492. var viewMatrix = this._scene.getViewMatrix();
  46493. effect.setTexture("diffuseSampler", this.particleTexture);
  46494. effect.setMatrix("view", viewMatrix);
  46495. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46496. if (this._isAnimationSheetEnabled) {
  46497. var baseSize = this.particleTexture.getBaseSize();
  46498. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  46499. }
  46500. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  46501. if (this._scene.clipPlane) {
  46502. var clipPlane = this._scene.clipPlane;
  46503. var invView = viewMatrix.clone();
  46504. invView.invert();
  46505. effect.setMatrix("invView", invView);
  46506. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  46507. }
  46508. // VBOs
  46509. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46510. // Draw order
  46511. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  46512. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  46513. }
  46514. else {
  46515. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46516. }
  46517. if (this.forceDepthWrite) {
  46518. engine.setDepthWrite(true);
  46519. }
  46520. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this.particles.length * 6);
  46521. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46522. return this.particles.length;
  46523. };
  46524. ParticleSystem.prototype.dispose = function () {
  46525. if (this._vertexBuffer) {
  46526. this._vertexBuffer.dispose();
  46527. this._vertexBuffer = null;
  46528. }
  46529. if (this._indexBuffer) {
  46530. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46531. this._indexBuffer = null;
  46532. }
  46533. if (this.particleTexture) {
  46534. this.particleTexture.dispose();
  46535. this.particleTexture = null;
  46536. }
  46537. // Remove from scene
  46538. var index = this._scene.particleSystems.indexOf(this);
  46539. if (index > -1) {
  46540. this._scene.particleSystems.splice(index, 1);
  46541. }
  46542. // Callback
  46543. this.onDisposeObservable.notifyObservers(this);
  46544. this.onDisposeObservable.clear();
  46545. };
  46546. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  46547. if (radius === void 0) { radius = 1; }
  46548. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  46549. this.particleEmitterType = particleEmitter;
  46550. return particleEmitter;
  46551. };
  46552. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  46553. if (radius === void 0) { radius = 1; }
  46554. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  46555. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  46556. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  46557. this.particleEmitterType = particleEmitter;
  46558. return particleEmitter;
  46559. };
  46560. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  46561. if (radius === void 0) { radius = 1; }
  46562. if (angle === void 0) { angle = Math.PI / 4; }
  46563. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  46564. this.particleEmitterType = particleEmitter;
  46565. return particleEmitter;
  46566. };
  46567. // 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.
  46568. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  46569. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  46570. this.direction1 = direction1;
  46571. this.direction2 = direction2;
  46572. this.minEmitBox = minEmitBox;
  46573. this.maxEmitBox = maxEmitBox;
  46574. this.particleEmitterType = particleEmitter;
  46575. return particleEmitter;
  46576. };
  46577. ParticleSystem.randomNumber = function (min, max) {
  46578. if (min === max) {
  46579. return (min);
  46580. }
  46581. var random = Math.random();
  46582. return ((random * (max - min)) + min);
  46583. };
  46584. // Clone
  46585. ParticleSystem.prototype.clone = function (name, newEmitter) {
  46586. var custom = null;
  46587. var program = null;
  46588. if (this.customShader != null) {
  46589. program = this.customShader;
  46590. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46591. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46592. }
  46593. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  46594. result.customShader = program;
  46595. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  46596. if (newEmitter === undefined) {
  46597. newEmitter = this.emitter;
  46598. }
  46599. result.emitter = newEmitter;
  46600. if (this.particleTexture) {
  46601. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  46602. }
  46603. if (!this.preventAutoStart) {
  46604. result.start();
  46605. }
  46606. return result;
  46607. };
  46608. ParticleSystem.prototype.serialize = function () {
  46609. var serializationObject = {};
  46610. serializationObject.name = this.name;
  46611. serializationObject.id = this.id;
  46612. // Emitter
  46613. if (this.emitter.position) {
  46614. var emitterMesh = this.emitter;
  46615. serializationObject.emitterId = emitterMesh.id;
  46616. }
  46617. else {
  46618. var emitterPosition = this.emitter;
  46619. serializationObject.emitter = emitterPosition.asArray();
  46620. }
  46621. serializationObject.capacity = this.getCapacity();
  46622. if (this.particleTexture) {
  46623. serializationObject.textureName = this.particleTexture.name;
  46624. }
  46625. // Animations
  46626. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  46627. // Particle system
  46628. serializationObject.minAngularSpeed = this.minAngularSpeed;
  46629. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  46630. serializationObject.minSize = this.minSize;
  46631. serializationObject.maxSize = this.maxSize;
  46632. serializationObject.minEmitPower = this.minEmitPower;
  46633. serializationObject.maxEmitPower = this.maxEmitPower;
  46634. serializationObject.minLifeTime = this.minLifeTime;
  46635. serializationObject.maxLifeTime = this.maxLifeTime;
  46636. serializationObject.emitRate = this.emitRate;
  46637. serializationObject.minEmitBox = this.minEmitBox.asArray();
  46638. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  46639. serializationObject.gravity = this.gravity.asArray();
  46640. serializationObject.direction1 = this.direction1.asArray();
  46641. serializationObject.direction2 = this.direction2.asArray();
  46642. serializationObject.color1 = this.color1.asArray();
  46643. serializationObject.color2 = this.color2.asArray();
  46644. serializationObject.colorDead = this.colorDead.asArray();
  46645. serializationObject.updateSpeed = this.updateSpeed;
  46646. serializationObject.targetStopDuration = this.targetStopDuration;
  46647. serializationObject.textureMask = this.textureMask.asArray();
  46648. serializationObject.blendMode = this.blendMode;
  46649. serializationObject.customShader = this.customShader;
  46650. serializationObject.preventAutoStart = this.preventAutoStart;
  46651. serializationObject.startSpriteCellID = this.startSpriteCellID;
  46652. serializationObject.endSpriteCellID = this.endSpriteCellID;
  46653. serializationObject.spriteCellLoop = this.spriteCellLoop;
  46654. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  46655. serializationObject.spriteCellWidth = this.spriteCellWidth;
  46656. serializationObject.spriteCellHeight = this.spriteCellHeight;
  46657. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  46658. return serializationObject;
  46659. };
  46660. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  46661. var name = parsedParticleSystem.name;
  46662. var custom = null;
  46663. var program = null;
  46664. if (parsedParticleSystem.customShader) {
  46665. program = parsedParticleSystem.customShader;
  46666. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46667. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46668. }
  46669. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  46670. particleSystem.customShader = program;
  46671. if (parsedParticleSystem.id) {
  46672. particleSystem.id = parsedParticleSystem.id;
  46673. }
  46674. // Auto start
  46675. if (parsedParticleSystem.preventAutoStart) {
  46676. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  46677. }
  46678. // Texture
  46679. if (parsedParticleSystem.textureName) {
  46680. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  46681. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  46682. }
  46683. // Emitter
  46684. if (parsedParticleSystem.emitterId) {
  46685. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  46686. }
  46687. else {
  46688. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  46689. }
  46690. // Animations
  46691. if (parsedParticleSystem.animations) {
  46692. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  46693. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  46694. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  46695. }
  46696. }
  46697. if (parsedParticleSystem.autoAnimate) {
  46698. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  46699. }
  46700. // Particle system
  46701. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  46702. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  46703. particleSystem.minSize = parsedParticleSystem.minSize;
  46704. particleSystem.maxSize = parsedParticleSystem.maxSize;
  46705. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  46706. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  46707. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  46708. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  46709. particleSystem.emitRate = parsedParticleSystem.emitRate;
  46710. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  46711. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  46712. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  46713. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  46714. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  46715. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  46716. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  46717. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  46718. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  46719. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  46720. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  46721. particleSystem.blendMode = parsedParticleSystem.blendMode;
  46722. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  46723. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  46724. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  46725. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  46726. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  46727. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  46728. if (!particleSystem.preventAutoStart) {
  46729. particleSystem.start();
  46730. }
  46731. return particleSystem;
  46732. };
  46733. // Statics
  46734. ParticleSystem.BLENDMODE_ONEONE = 0;
  46735. ParticleSystem.BLENDMODE_STANDARD = 1;
  46736. return ParticleSystem;
  46737. }());
  46738. BABYLON.ParticleSystem = ParticleSystem;
  46739. })(BABYLON || (BABYLON = {}));
  46740. //# sourceMappingURL=babylon.particleSystem.js.map
  46741. var BABYLON;
  46742. (function (BABYLON) {
  46743. var BoxParticleEmitter = /** @class */ (function () {
  46744. // to be updated like the rest of emitters when breaking changes.
  46745. // all property should be come public variables and passed through constructor.
  46746. function BoxParticleEmitter(_particleSystem) {
  46747. this._particleSystem = _particleSystem;
  46748. }
  46749. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  46750. get: function () {
  46751. return this._particleSystem.direction1;
  46752. },
  46753. set: function (value) {
  46754. this._particleSystem.direction1 = value;
  46755. },
  46756. enumerable: true,
  46757. configurable: true
  46758. });
  46759. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  46760. get: function () {
  46761. return this._particleSystem.direction2;
  46762. },
  46763. set: function (value) {
  46764. this._particleSystem.direction2 = value;
  46765. },
  46766. enumerable: true,
  46767. configurable: true
  46768. });
  46769. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  46770. get: function () {
  46771. return this._particleSystem.minEmitBox;
  46772. },
  46773. set: function (value) {
  46774. this._particleSystem.minEmitBox = value;
  46775. },
  46776. enumerable: true,
  46777. configurable: true
  46778. });
  46779. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  46780. get: function () {
  46781. return this._particleSystem.maxEmitBox;
  46782. },
  46783. set: function (value) {
  46784. this._particleSystem.maxEmitBox = value;
  46785. },
  46786. enumerable: true,
  46787. configurable: true
  46788. });
  46789. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46790. var randX = BABYLON.ParticleSystem.randomNumber(this.direction1.x, this.direction2.x);
  46791. var randY = BABYLON.ParticleSystem.randomNumber(this.direction1.y, this.direction2.y);
  46792. var randZ = BABYLON.ParticleSystem.randomNumber(this.direction1.z, this.direction2.z);
  46793. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46794. };
  46795. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46796. var randX = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.x, this.maxEmitBox.x);
  46797. var randY = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.y, this.maxEmitBox.y);
  46798. var randZ = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.z, this.maxEmitBox.z);
  46799. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  46800. };
  46801. return BoxParticleEmitter;
  46802. }());
  46803. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  46804. })(BABYLON || (BABYLON = {}));
  46805. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  46806. var BABYLON;
  46807. (function (BABYLON) {
  46808. var ConeParticleEmitter = /** @class */ (function () {
  46809. function ConeParticleEmitter(radius, angle) {
  46810. this.radius = radius;
  46811. this.angle = angle;
  46812. }
  46813. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46814. if (this.angle === 0) {
  46815. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  46816. }
  46817. else {
  46818. var phi = BABYLON.ParticleSystem.randomNumber(0, 2 * Math.PI);
  46819. var theta = BABYLON.ParticleSystem.randomNumber(0, this.angle);
  46820. var randX = Math.cos(phi) * Math.sin(theta);
  46821. var randY = Math.cos(theta);
  46822. var randZ = Math.sin(phi) * Math.sin(theta);
  46823. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46824. }
  46825. };
  46826. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46827. var s = BABYLON.ParticleSystem.randomNumber(0, Math.PI * 2);
  46828. var radius = BABYLON.ParticleSystem.randomNumber(0, this.radius);
  46829. var randX = radius * Math.sin(s);
  46830. var randZ = radius * Math.cos(s);
  46831. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, 0, randZ, worldMatrix, positionToUpdate);
  46832. };
  46833. return ConeParticleEmitter;
  46834. }());
  46835. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  46836. })(BABYLON || (BABYLON = {}));
  46837. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  46838. var BABYLON;
  46839. (function (BABYLON) {
  46840. var SphereParticleEmitter = /** @class */ (function () {
  46841. function SphereParticleEmitter(radius) {
  46842. this.radius = radius;
  46843. }
  46844. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46845. // measure the direction Vector from the emitter to the particle.
  46846. var direction = particle.position.subtract(worldMatrix.getTranslation());
  46847. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  46848. };
  46849. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46850. var phi = BABYLON.ParticleSystem.randomNumber(0, 2 * Math.PI);
  46851. var theta = BABYLON.ParticleSystem.randomNumber(0, Math.PI);
  46852. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  46853. var randY = this.radius * Math.cos(theta);
  46854. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  46855. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  46856. };
  46857. return SphereParticleEmitter;
  46858. }());
  46859. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  46860. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  46861. __extends(SphereDirectedParticleEmitter, _super);
  46862. function SphereDirectedParticleEmitter(radius, direction1, direction2) {
  46863. var _this = _super.call(this, radius) || this;
  46864. _this.direction1 = direction1;
  46865. _this.direction2 = direction2;
  46866. return _this;
  46867. }
  46868. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46869. var randX = BABYLON.ParticleSystem.randomNumber(this.direction1.x, this.direction2.x);
  46870. var randY = BABYLON.ParticleSystem.randomNumber(this.direction1.y, this.direction2.y);
  46871. var randZ = BABYLON.ParticleSystem.randomNumber(this.direction1.z, this.direction2.z);
  46872. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46873. };
  46874. return SphereDirectedParticleEmitter;
  46875. }(SphereParticleEmitter));
  46876. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  46877. })(BABYLON || (BABYLON = {}));
  46878. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  46879. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  46880. var BABYLON;
  46881. (function (BABYLON) {
  46882. var SolidParticle = /** @class */ (function () {
  46883. /**
  46884. * Creates a Solid Particle object.
  46885. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  46886. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  46887. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  46888. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  46889. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  46890. * `shapeId` (integer) is the model shape identifier in the SPS.
  46891. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  46892. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  46893. */
  46894. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  46895. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  46896. this.idx = 0; // particle global index
  46897. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  46898. this.position = BABYLON.Vector3.Zero(); // position
  46899. this.rotation = BABYLON.Vector3.Zero(); // rotation
  46900. this.scaling = BABYLON.Vector3.One(); // scaling
  46901. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  46902. this.velocity = BABYLON.Vector3.Zero(); // velocity
  46903. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  46904. this.alive = true; // alive
  46905. this.isVisible = true; // visibility
  46906. this._pos = 0; // index of this particle in the global "positions" array
  46907. this._ind = 0; // index of this particle in the global "indices" array
  46908. this.shapeId = 0; // model shape id
  46909. this.idxInShape = 0; // index of the particle in its shape id
  46910. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  46911. this.idx = particleIndex;
  46912. this._pos = positionIndex;
  46913. this._ind = indiceIndex;
  46914. this._model = model;
  46915. this.shapeId = shapeId;
  46916. this.idxInShape = idxInShape;
  46917. this._sps = sps;
  46918. if (modelBoundingInfo) {
  46919. this._modelBoundingInfo = modelBoundingInfo;
  46920. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  46921. }
  46922. }
  46923. Object.defineProperty(SolidParticle.prototype, "scale", {
  46924. /**
  46925. * legacy support, changed scale to scaling
  46926. */
  46927. get: function () {
  46928. return this.scaling;
  46929. },
  46930. set: function (scale) {
  46931. this.scaling = scale;
  46932. },
  46933. enumerable: true,
  46934. configurable: true
  46935. });
  46936. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  46937. /**
  46938. * legacy support, changed quaternion to rotationQuaternion
  46939. */
  46940. get: function () {
  46941. return this.rotationQuaternion;
  46942. },
  46943. set: function (q) {
  46944. this.rotationQuaternion = q;
  46945. },
  46946. enumerable: true,
  46947. configurable: true
  46948. });
  46949. /**
  46950. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  46951. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  46952. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  46953. */
  46954. SolidParticle.prototype.intersectsMesh = function (target) {
  46955. if (!this._boundingInfo || !target._boundingInfo) {
  46956. return false;
  46957. }
  46958. if (this._sps._bSphereOnly) {
  46959. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  46960. }
  46961. return this._boundingInfo.intersects(target._boundingInfo, false);
  46962. };
  46963. return SolidParticle;
  46964. }());
  46965. BABYLON.SolidParticle = SolidParticle;
  46966. var ModelShape = /** @class */ (function () {
  46967. /**
  46968. * 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.
  46969. * SPS internal tool, don't use it manually.
  46970. */
  46971. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  46972. this._indicesLength = 0; // length of the shape in the model indices array
  46973. this.shapeID = id;
  46974. this._shape = shape;
  46975. this._indicesLength = indicesLength;
  46976. this._shapeUV = shapeUV;
  46977. this._positionFunction = posFunction;
  46978. this._vertexFunction = vtxFunction;
  46979. }
  46980. return ModelShape;
  46981. }());
  46982. BABYLON.ModelShape = ModelShape;
  46983. var DepthSortedParticle = /** @class */ (function () {
  46984. function DepthSortedParticle() {
  46985. this.ind = 0; // index of the particle in the "indices" array
  46986. this.indicesLength = 0; // length of the particle shape in the "indices" array
  46987. this.sqDistance = 0.0; // squared distance from the particle to the camera
  46988. }
  46989. return DepthSortedParticle;
  46990. }());
  46991. BABYLON.DepthSortedParticle = DepthSortedParticle;
  46992. })(BABYLON || (BABYLON = {}));
  46993. //# sourceMappingURL=babylon.solidParticle.js.map
  46994. var BABYLON;
  46995. (function (BABYLON) {
  46996. /**
  46997. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  46998. */
  46999. var SolidParticleSystem = /** @class */ (function () {
  47000. /**
  47001. * Creates a SPS (Solid Particle System) object.
  47002. * `name` (String) is the SPS name, this will be the underlying mesh name.
  47003. * `scene` (Scene) is the scene in which the SPS is added.
  47004. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  47005. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  47006. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  47007. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  47008. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  47009. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  47010. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  47011. */
  47012. function SolidParticleSystem(name, scene, options) {
  47013. // public members
  47014. /**
  47015. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  47016. * Example : var p = SPS.particles[i];
  47017. */
  47018. this.particles = new Array();
  47019. /**
  47020. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  47021. */
  47022. this.nbParticles = 0;
  47023. /**
  47024. * If the particles must ever face the camera (default false). Useful for planar particles.
  47025. */
  47026. this.billboard = false;
  47027. /**
  47028. * Recompute normals when adding a shape
  47029. */
  47030. this.recomputeNormals = true;
  47031. /**
  47032. * This a counter ofr your own usage. It's not set by any SPS functions.
  47033. */
  47034. this.counter = 0;
  47035. /**
  47036. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  47037. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  47038. */
  47039. this.vars = {};
  47040. this._positions = new Array();
  47041. this._indices = new Array();
  47042. this._normals = new Array();
  47043. this._colors = new Array();
  47044. this._uvs = new Array();
  47045. this._index = 0; // indices index
  47046. this._updatable = true;
  47047. this._pickable = false;
  47048. this._isVisibilityBoxLocked = false;
  47049. this._alwaysVisible = false;
  47050. this._depthSort = false;
  47051. this._shapeCounter = 0;
  47052. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  47053. this._color = new BABYLON.Color4(0, 0, 0, 0);
  47054. this._computeParticleColor = true;
  47055. this._computeParticleTexture = true;
  47056. this._computeParticleRotation = true;
  47057. this._computeParticleVertex = false;
  47058. this._computeBoundingBox = false;
  47059. this._depthSortParticles = true;
  47060. this._cam_axisZ = BABYLON.Vector3.Zero();
  47061. this._cam_axisY = BABYLON.Vector3.Zero();
  47062. this._cam_axisX = BABYLON.Vector3.Zero();
  47063. this._axisZ = BABYLON.Axis.Z;
  47064. this._camDir = BABYLON.Vector3.Zero();
  47065. this._camInvertedPosition = BABYLON.Vector3.Zero();
  47066. this._rotMatrix = new BABYLON.Matrix();
  47067. this._invertMatrix = new BABYLON.Matrix();
  47068. this._rotated = BABYLON.Vector3.Zero();
  47069. this._quaternion = new BABYLON.Quaternion();
  47070. this._vertex = BABYLON.Vector3.Zero();
  47071. this._normal = BABYLON.Vector3.Zero();
  47072. this._yaw = 0.0;
  47073. this._pitch = 0.0;
  47074. this._roll = 0.0;
  47075. this._halfroll = 0.0;
  47076. this._halfpitch = 0.0;
  47077. this._halfyaw = 0.0;
  47078. this._sinRoll = 0.0;
  47079. this._cosRoll = 0.0;
  47080. this._sinPitch = 0.0;
  47081. this._cosPitch = 0.0;
  47082. this._sinYaw = 0.0;
  47083. this._cosYaw = 0.0;
  47084. this._mustUnrotateFixedNormals = false;
  47085. this._minimum = BABYLON.Tmp.Vector3[0];
  47086. this._maximum = BABYLON.Tmp.Vector3[1];
  47087. this._minBbox = BABYLON.Tmp.Vector3[4];
  47088. this._maxBbox = BABYLON.Tmp.Vector3[5];
  47089. this._particlesIntersect = false;
  47090. this._depthSortFunction = function (p1, p2) {
  47091. return (p2.sqDistance - p1.sqDistance);
  47092. };
  47093. this._needs32Bits = false;
  47094. this._bSphereOnly = false;
  47095. this._bSphereRadiusFactor = 1.0;
  47096. this.name = name;
  47097. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47098. this._camera = scene.activeCamera;
  47099. this._pickable = options ? options.isPickable : false;
  47100. this._depthSort = options ? options.enableDepthSort : false;
  47101. this._particlesIntersect = options ? options.particleIntersection : false;
  47102. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  47103. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  47104. if (options && options.updatable) {
  47105. this._updatable = options.updatable;
  47106. }
  47107. else {
  47108. this._updatable = true;
  47109. }
  47110. if (this._pickable) {
  47111. this.pickedParticles = [];
  47112. }
  47113. if (this._depthSort) {
  47114. this.depthSortedParticles = [];
  47115. }
  47116. }
  47117. /**
  47118. * Builds the SPS underlying mesh. Returns a standard Mesh.
  47119. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  47120. */
  47121. SolidParticleSystem.prototype.buildMesh = function () {
  47122. if (this.nbParticles === 0) {
  47123. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  47124. this.addShape(triangle, 1);
  47125. triangle.dispose();
  47126. }
  47127. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  47128. this._positions32 = new Float32Array(this._positions);
  47129. this._uvs32 = new Float32Array(this._uvs);
  47130. this._colors32 = new Float32Array(this._colors);
  47131. if (this.recomputeNormals) {
  47132. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  47133. }
  47134. this._normals32 = new Float32Array(this._normals);
  47135. this._fixedNormal32 = new Float32Array(this._normals);
  47136. if (this._mustUnrotateFixedNormals) {
  47137. this._unrotateFixedNormals();
  47138. }
  47139. var vertexData = new BABYLON.VertexData();
  47140. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  47141. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  47142. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  47143. if (this._uvs32) {
  47144. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  47145. ;
  47146. }
  47147. if (this._colors32) {
  47148. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  47149. }
  47150. var mesh = new BABYLON.Mesh(this.name, this._scene);
  47151. vertexData.applyToMesh(mesh, this._updatable);
  47152. this.mesh = mesh;
  47153. this.mesh.isPickable = this._pickable;
  47154. // free memory
  47155. if (!this._depthSort) {
  47156. this._indices = null;
  47157. }
  47158. this._positions = null;
  47159. this._normals = null;
  47160. this._uvs = null;
  47161. this._colors = null;
  47162. if (!this._updatable) {
  47163. this.particles.length = 0;
  47164. }
  47165. return mesh;
  47166. };
  47167. /**
  47168. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  47169. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  47170. * Thus the particles generated from `digest()` have their property `position` set yet.
  47171. * `mesh` ( Mesh ) is the mesh to be digested
  47172. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  47173. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  47174. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  47175. */
  47176. SolidParticleSystem.prototype.digest = function (mesh, options) {
  47177. var size = (options && options.facetNb) || 1;
  47178. var number = (options && options.number) || 0;
  47179. var delta = (options && options.delta) || 0;
  47180. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47181. var meshInd = mesh.getIndices();
  47182. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47183. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47184. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47185. var f = 0; // facet counter
  47186. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  47187. // compute size from number
  47188. if (number) {
  47189. number = (number > totalFacets) ? totalFacets : number;
  47190. size = Math.round(totalFacets / number);
  47191. delta = 0;
  47192. }
  47193. else {
  47194. size = (size > totalFacets) ? totalFacets : size;
  47195. }
  47196. var facetPos = []; // submesh positions
  47197. var facetInd = []; // submesh indices
  47198. var facetUV = []; // submesh UV
  47199. var facetCol = []; // submesh colors
  47200. var barycenter = BABYLON.Tmp.Vector3[0];
  47201. var sizeO = size;
  47202. while (f < totalFacets) {
  47203. size = sizeO + Math.floor((1 + delta) * Math.random());
  47204. if (f > totalFacets - size) {
  47205. size = totalFacets - f;
  47206. }
  47207. // reset temp arrays
  47208. facetPos.length = 0;
  47209. facetInd.length = 0;
  47210. facetUV.length = 0;
  47211. facetCol.length = 0;
  47212. // iterate over "size" facets
  47213. var fi = 0;
  47214. for (var j = f * 3; j < (f + size) * 3; j++) {
  47215. facetInd.push(fi);
  47216. var i = meshInd[j];
  47217. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  47218. if (meshUV) {
  47219. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  47220. }
  47221. if (meshCol) {
  47222. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  47223. }
  47224. fi++;
  47225. }
  47226. // create a model shape for each single particle
  47227. var idx = this.nbParticles;
  47228. var shape = this._posToShape(facetPos);
  47229. var shapeUV = this._uvsToShapeUV(facetUV);
  47230. // compute the barycenter of the shape
  47231. var v;
  47232. for (v = 0; v < shape.length; v++) {
  47233. barycenter.addInPlace(shape[v]);
  47234. }
  47235. barycenter.scaleInPlace(1 / shape.length);
  47236. // shift the shape from its barycenter to the origin
  47237. for (v = 0; v < shape.length; v++) {
  47238. shape[v].subtractInPlace(barycenter);
  47239. }
  47240. var bInfo;
  47241. if (this._particlesIntersect) {
  47242. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  47243. }
  47244. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  47245. // add the particle in the SPS
  47246. var currentPos = this._positions.length;
  47247. var currentInd = this._indices.length;
  47248. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  47249. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  47250. // initialize the particle position
  47251. this.particles[this.nbParticles].position.addInPlace(barycenter);
  47252. this._index += shape.length;
  47253. idx++;
  47254. this.nbParticles++;
  47255. this._shapeCounter++;
  47256. f += size;
  47257. }
  47258. return this;
  47259. };
  47260. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  47261. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  47262. var index = 0;
  47263. var idx = 0;
  47264. for (var p = 0; p < this.particles.length; p++) {
  47265. this._particle = this.particles[p];
  47266. this._shape = this._particle._model._shape;
  47267. if (this._particle.rotationQuaternion) {
  47268. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47269. }
  47270. else {
  47271. this._yaw = this._particle.rotation.y;
  47272. this._pitch = this._particle.rotation.x;
  47273. this._roll = this._particle.rotation.z;
  47274. this._quaternionRotationYPR();
  47275. }
  47276. this._quaternionToRotationMatrix();
  47277. this._rotMatrix.invertToRef(this._invertMatrix);
  47278. for (var pt = 0; pt < this._shape.length; pt++) {
  47279. idx = index + pt * 3;
  47280. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  47281. this._fixedNormal32[idx] = this._normal.x;
  47282. this._fixedNormal32[idx + 1] = this._normal.y;
  47283. this._fixedNormal32[idx + 2] = this._normal.z;
  47284. }
  47285. index = idx + 3;
  47286. }
  47287. };
  47288. //reset copy
  47289. SolidParticleSystem.prototype._resetCopy = function () {
  47290. this._copy.position.x = 0;
  47291. this._copy.position.y = 0;
  47292. this._copy.position.z = 0;
  47293. this._copy.rotation.x = 0;
  47294. this._copy.rotation.y = 0;
  47295. this._copy.rotation.z = 0;
  47296. this._copy.rotationQuaternion = null;
  47297. this._copy.scaling.x = 1.0;
  47298. this._copy.scaling.y = 1.0;
  47299. this._copy.scaling.z = 1.0;
  47300. this._copy.uvs.x = 0;
  47301. this._copy.uvs.y = 0;
  47302. this._copy.uvs.z = 1.0;
  47303. this._copy.uvs.w = 1.0;
  47304. this._copy.color = null;
  47305. };
  47306. // _meshBuilder : inserts the shape model in the global SPS mesh
  47307. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  47308. var i;
  47309. var u = 0;
  47310. var c = 0;
  47311. var n = 0;
  47312. this._resetCopy();
  47313. if (options && options.positionFunction) {
  47314. options.positionFunction(this._copy, idx, idxInShape);
  47315. this._mustUnrotateFixedNormals = true;
  47316. }
  47317. if (this._copy.rotationQuaternion) {
  47318. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47319. }
  47320. else {
  47321. this._yaw = this._copy.rotation.y;
  47322. this._pitch = this._copy.rotation.x;
  47323. this._roll = this._copy.rotation.z;
  47324. this._quaternionRotationYPR();
  47325. }
  47326. this._quaternionToRotationMatrix();
  47327. for (i = 0; i < shape.length; i++) {
  47328. this._vertex.x = shape[i].x;
  47329. this._vertex.y = shape[i].y;
  47330. this._vertex.z = shape[i].z;
  47331. if (options && options.vertexFunction) {
  47332. options.vertexFunction(this._copy, this._vertex, i);
  47333. }
  47334. this._vertex.x *= this._copy.scaling.x;
  47335. this._vertex.y *= this._copy.scaling.y;
  47336. this._vertex.z *= this._copy.scaling.z;
  47337. this._vertex.x += this._copy.pivot.x;
  47338. this._vertex.y += this._copy.pivot.y;
  47339. this._vertex.z += this._copy.pivot.z;
  47340. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47341. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  47342. if (meshUV) {
  47343. 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);
  47344. u += 2;
  47345. }
  47346. if (this._copy.color) {
  47347. this._color = this._copy.color;
  47348. }
  47349. else if (meshCol && meshCol[c] !== undefined) {
  47350. this._color.r = meshCol[c];
  47351. this._color.g = meshCol[c + 1];
  47352. this._color.b = meshCol[c + 2];
  47353. this._color.a = meshCol[c + 3];
  47354. }
  47355. else {
  47356. this._color.r = 1.0;
  47357. this._color.g = 1.0;
  47358. this._color.b = 1.0;
  47359. this._color.a = 1.0;
  47360. }
  47361. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  47362. c += 4;
  47363. if (!this.recomputeNormals && meshNor) {
  47364. this._normal.x = meshNor[n];
  47365. this._normal.y = meshNor[n + 1];
  47366. this._normal.z = meshNor[n + 2];
  47367. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  47368. normals.push(this._normal.x, this._normal.y, this._normal.z);
  47369. n += 3;
  47370. }
  47371. }
  47372. for (i = 0; i < meshInd.length; i++) {
  47373. var current_ind = p + meshInd[i];
  47374. indices.push(current_ind);
  47375. if (current_ind > 65535) {
  47376. this._needs32Bits = true;
  47377. }
  47378. }
  47379. if (this._pickable) {
  47380. var nbfaces = meshInd.length / 3;
  47381. for (i = 0; i < nbfaces; i++) {
  47382. this.pickedParticles.push({ idx: idx, faceId: i });
  47383. }
  47384. }
  47385. if (this._depthSort) {
  47386. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  47387. }
  47388. return this._copy;
  47389. };
  47390. // returns a shape array from positions array
  47391. SolidParticleSystem.prototype._posToShape = function (positions) {
  47392. var shape = [];
  47393. for (var i = 0; i < positions.length; i += 3) {
  47394. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  47395. }
  47396. return shape;
  47397. };
  47398. // returns a shapeUV array from a Vector4 uvs
  47399. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  47400. var shapeUV = [];
  47401. if (uvs) {
  47402. for (var i = 0; i < uvs.length; i++)
  47403. shapeUV.push(uvs[i]);
  47404. }
  47405. return shapeUV;
  47406. };
  47407. // adds a new particle object in the particles array
  47408. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  47409. if (bInfo === void 0) { bInfo = null; }
  47410. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  47411. this.particles.push(sp);
  47412. return sp;
  47413. };
  47414. /**
  47415. * Adds some particles to the SPS from the model shape. Returns the shape id.
  47416. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  47417. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  47418. * `nb` (positive integer) the number of particles to be created from this model
  47419. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  47420. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  47421. */
  47422. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  47423. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47424. var meshInd = mesh.getIndices();
  47425. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47426. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47427. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47428. var bbInfo;
  47429. if (this._particlesIntersect) {
  47430. bbInfo = mesh.getBoundingInfo();
  47431. }
  47432. var shape = this._posToShape(meshPos);
  47433. var shapeUV = this._uvsToShapeUV(meshUV);
  47434. var posfunc = options ? options.positionFunction : null;
  47435. var vtxfunc = options ? options.vertexFunction : null;
  47436. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  47437. // particles
  47438. var sp;
  47439. var currentCopy;
  47440. var idx = this.nbParticles;
  47441. for (var i = 0; i < nb; i++) {
  47442. var currentPos = this._positions.length;
  47443. var currentInd = this._indices.length;
  47444. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  47445. if (this._updatable) {
  47446. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  47447. sp.position.copyFrom(currentCopy.position);
  47448. sp.rotation.copyFrom(currentCopy.rotation);
  47449. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  47450. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  47451. }
  47452. if (currentCopy.color && sp.color) {
  47453. sp.color.copyFrom(currentCopy.color);
  47454. }
  47455. sp.scaling.copyFrom(currentCopy.scaling);
  47456. sp.uvs.copyFrom(currentCopy.uvs);
  47457. }
  47458. this._index += shape.length;
  47459. idx++;
  47460. }
  47461. this.nbParticles += nb;
  47462. this._shapeCounter++;
  47463. return this._shapeCounter - 1;
  47464. };
  47465. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  47466. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  47467. this._resetCopy();
  47468. if (particle._model._positionFunction) {
  47469. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  47470. }
  47471. if (this._copy.rotationQuaternion) {
  47472. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47473. }
  47474. else {
  47475. this._yaw = this._copy.rotation.y;
  47476. this._pitch = this._copy.rotation.x;
  47477. this._roll = this._copy.rotation.z;
  47478. this._quaternionRotationYPR();
  47479. }
  47480. this._quaternionToRotationMatrix();
  47481. this._shape = particle._model._shape;
  47482. for (var pt = 0; pt < this._shape.length; pt++) {
  47483. this._vertex.x = this._shape[pt].x;
  47484. this._vertex.y = this._shape[pt].y;
  47485. this._vertex.z = this._shape[pt].z;
  47486. if (particle._model._vertexFunction) {
  47487. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  47488. }
  47489. this._vertex.x *= this._copy.scaling.x;
  47490. this._vertex.y *= this._copy.scaling.y;
  47491. this._vertex.z *= this._copy.scaling.z;
  47492. this._vertex.x += this._copy.pivot.x;
  47493. this._vertex.y += this._copy.pivot.y;
  47494. this._vertex.z += this._copy.pivot.z;
  47495. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47496. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  47497. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  47498. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  47499. }
  47500. particle.position.x = 0.0;
  47501. particle.position.y = 0.0;
  47502. particle.position.z = 0.0;
  47503. particle.rotation.x = 0.0;
  47504. particle.rotation.y = 0.0;
  47505. particle.rotation.z = 0.0;
  47506. particle.rotationQuaternion = null;
  47507. particle.scaling.x = 1.0;
  47508. particle.scaling.y = 1.0;
  47509. particle.scaling.z = 1.0;
  47510. };
  47511. /**
  47512. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  47513. * Returns the SPS.
  47514. */
  47515. SolidParticleSystem.prototype.rebuildMesh = function () {
  47516. for (var p = 0; p < this.particles.length; p++) {
  47517. this._rebuildParticle(this.particles[p]);
  47518. }
  47519. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47520. return this;
  47521. };
  47522. /**
  47523. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  47524. * This method calls `updateParticle()` for each particle of the SPS.
  47525. * For an animated SPS, it is usually called within the render loop.
  47526. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  47527. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  47528. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  47529. * Returns the SPS.
  47530. */
  47531. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  47532. if (start === void 0) { start = 0; }
  47533. if (end === void 0) { end = this.nbParticles - 1; }
  47534. if (update === void 0) { update = true; }
  47535. if (!this._updatable) {
  47536. return this;
  47537. }
  47538. // custom beforeUpdate
  47539. this.beforeUpdateParticles(start, end, update);
  47540. this._cam_axisX.x = 1.0;
  47541. this._cam_axisX.y = 0.0;
  47542. this._cam_axisX.z = 0.0;
  47543. this._cam_axisY.x = 0.0;
  47544. this._cam_axisY.y = 1.0;
  47545. this._cam_axisY.z = 0.0;
  47546. this._cam_axisZ.x = 0.0;
  47547. this._cam_axisZ.y = 0.0;
  47548. this._cam_axisZ.z = 1.0;
  47549. // cases when the World Matrix is to be computed first
  47550. if (this.billboard || this._depthSort) {
  47551. this.mesh.computeWorldMatrix(true);
  47552. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  47553. }
  47554. // if the particles will always face the camera
  47555. if (this.billboard) {
  47556. // compute the camera position and un-rotate it by the current mesh rotation
  47557. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  47558. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  47559. this._cam_axisZ.normalize();
  47560. // same for camera up vector extracted from the cam view matrix
  47561. var view = this._camera.getViewMatrix(true);
  47562. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  47563. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  47564. this._cam_axisY.normalize();
  47565. this._cam_axisX.normalize();
  47566. }
  47567. // if depthSort, compute the camera global position in the mesh local system
  47568. if (this._depthSort) {
  47569. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  47570. }
  47571. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  47572. var idx = 0; // current position index in the global array positions32
  47573. var index = 0; // position start index in the global array positions32 of the current particle
  47574. var colidx = 0; // current color index in the global array colors32
  47575. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  47576. var uvidx = 0; // current uv index in the global array uvs32
  47577. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  47578. var pt = 0; // current index in the particle model shape
  47579. if (this.mesh.isFacetDataEnabled) {
  47580. this._computeBoundingBox = true;
  47581. }
  47582. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  47583. if (this._computeBoundingBox) {
  47584. if (start == 0 && end == this.nbParticles - 1) {
  47585. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  47586. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  47587. }
  47588. else {
  47589. if (this.mesh._boundingInfo) {
  47590. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  47591. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  47592. }
  47593. }
  47594. }
  47595. // particle loop
  47596. index = this.particles[start]._pos;
  47597. var vpos = (index / 3) | 0;
  47598. colorIndex = vpos * 4;
  47599. uvIndex = vpos * 2;
  47600. for (var p = start; p <= end; p++) {
  47601. this._particle = this.particles[p];
  47602. this._shape = this._particle._model._shape;
  47603. this._shapeUV = this._particle._model._shapeUV;
  47604. // call to custom user function to update the particle properties
  47605. this.updateParticle(this._particle);
  47606. // camera-particle distance for depth sorting
  47607. if (this._depthSort && this._depthSortParticles) {
  47608. var dsp = this.depthSortedParticles[p];
  47609. dsp.ind = this._particle._ind;
  47610. dsp.indicesLength = this._particle._model._indicesLength;
  47611. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  47612. }
  47613. // skip the computations for inactive or already invisible particles
  47614. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  47615. // increment indexes for the next particle
  47616. pt = this._shape.length;
  47617. index += pt * 3;
  47618. colorIndex += pt * 4;
  47619. uvIndex += pt * 2;
  47620. continue;
  47621. }
  47622. if (this._particle.isVisible) {
  47623. this._particle._stillInvisible = false; // un-mark permanent invisibility
  47624. // particle rotation matrix
  47625. if (this.billboard) {
  47626. this._particle.rotation.x = 0.0;
  47627. this._particle.rotation.y = 0.0;
  47628. }
  47629. if (this._computeParticleRotation || this.billboard) {
  47630. if (this._particle.rotationQuaternion) {
  47631. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47632. }
  47633. else {
  47634. this._yaw = this._particle.rotation.y;
  47635. this._pitch = this._particle.rotation.x;
  47636. this._roll = this._particle.rotation.z;
  47637. this._quaternionRotationYPR();
  47638. }
  47639. this._quaternionToRotationMatrix();
  47640. }
  47641. // particle vertex loop
  47642. for (pt = 0; pt < this._shape.length; pt++) {
  47643. idx = index + pt * 3;
  47644. colidx = colorIndex + pt * 4;
  47645. uvidx = uvIndex + pt * 2;
  47646. this._vertex.x = this._shape[pt].x;
  47647. this._vertex.y = this._shape[pt].y;
  47648. this._vertex.z = this._shape[pt].z;
  47649. if (this._computeParticleVertex) {
  47650. this.updateParticleVertex(this._particle, this._vertex, pt);
  47651. }
  47652. // positions
  47653. this._vertex.x *= this._particle.scaling.x;
  47654. this._vertex.y *= this._particle.scaling.y;
  47655. this._vertex.z *= this._particle.scaling.z;
  47656. this._vertex.x += this._particle.pivot.x;
  47657. this._vertex.y += this._particle.pivot.y;
  47658. this._vertex.z += this._particle.pivot.z;
  47659. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47660. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47661. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47662. 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;
  47663. 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;
  47664. 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;
  47665. if (this._computeBoundingBox) {
  47666. if (this._positions32[idx] < this._minimum.x) {
  47667. this._minimum.x = this._positions32[idx];
  47668. }
  47669. if (this._positions32[idx] > this._maximum.x) {
  47670. this._maximum.x = this._positions32[idx];
  47671. }
  47672. if (this._positions32[idx + 1] < this._minimum.y) {
  47673. this._minimum.y = this._positions32[idx + 1];
  47674. }
  47675. if (this._positions32[idx + 1] > this._maximum.y) {
  47676. this._maximum.y = this._positions32[idx + 1];
  47677. }
  47678. if (this._positions32[idx + 2] < this._minimum.z) {
  47679. this._minimum.z = this._positions32[idx + 2];
  47680. }
  47681. if (this._positions32[idx + 2] > this._maximum.z) {
  47682. this._maximum.z = this._positions32[idx + 2];
  47683. }
  47684. }
  47685. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  47686. if (!this._computeParticleVertex) {
  47687. this._normal.x = this._fixedNormal32[idx];
  47688. this._normal.y = this._fixedNormal32[idx + 1];
  47689. this._normal.z = this._fixedNormal32[idx + 2];
  47690. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  47691. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  47692. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  47693. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  47694. 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;
  47695. 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;
  47696. }
  47697. if (this._computeParticleColor && this._particle.color) {
  47698. this._colors32[colidx] = this._particle.color.r;
  47699. this._colors32[colidx + 1] = this._particle.color.g;
  47700. this._colors32[colidx + 2] = this._particle.color.b;
  47701. this._colors32[colidx + 3] = this._particle.color.a;
  47702. }
  47703. if (this._computeParticleTexture) {
  47704. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47705. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47706. }
  47707. }
  47708. }
  47709. else {
  47710. this._particle._stillInvisible = true; // mark the particle as invisible
  47711. for (pt = 0; pt < this._shape.length; pt++) {
  47712. idx = index + pt * 3;
  47713. colidx = colorIndex + pt * 4;
  47714. uvidx = uvIndex + pt * 2;
  47715. this._positions32[idx] = 0.0;
  47716. this._positions32[idx + 1] = 0.0;
  47717. this._positions32[idx + 2] = 0.0;
  47718. this._normals32[idx] = 0.0;
  47719. this._normals32[idx + 1] = 0.0;
  47720. this._normals32[idx + 2] = 0.0;
  47721. if (this._computeParticleColor && this._particle.color) {
  47722. this._colors32[colidx] = this._particle.color.r;
  47723. this._colors32[colidx + 1] = this._particle.color.g;
  47724. this._colors32[colidx + 2] = this._particle.color.b;
  47725. this._colors32[colidx + 3] = this._particle.color.a;
  47726. }
  47727. if (this._computeParticleTexture) {
  47728. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47729. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47730. }
  47731. }
  47732. }
  47733. // if the particle intersections must be computed : update the bbInfo
  47734. if (this._particlesIntersect) {
  47735. var bInfo = this._particle._boundingInfo;
  47736. var bBox = bInfo.boundingBox;
  47737. var bSphere = bInfo.boundingSphere;
  47738. if (!this._bSphereOnly) {
  47739. // place, scale and rotate the particle bbox within the SPS local system, then update it
  47740. for (var b = 0; b < bBox.vectors.length; b++) {
  47741. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  47742. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  47743. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  47744. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47745. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47746. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47747. 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;
  47748. 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;
  47749. 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;
  47750. }
  47751. bBox._update(this.mesh._worldMatrix);
  47752. }
  47753. // place and scale the particle bouding sphere in the SPS local system, then update it
  47754. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  47755. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  47756. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  47757. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  47758. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  47759. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  47760. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  47761. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  47762. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  47763. 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));
  47764. bSphere._update(this.mesh._worldMatrix);
  47765. }
  47766. // increment indexes for the next particle
  47767. index = idx + 3;
  47768. colorIndex = colidx + 4;
  47769. uvIndex = uvidx + 2;
  47770. }
  47771. // if the VBO must be updated
  47772. if (update) {
  47773. if (this._computeParticleColor) {
  47774. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  47775. }
  47776. if (this._computeParticleTexture) {
  47777. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  47778. }
  47779. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47780. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  47781. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  47782. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  47783. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  47784. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  47785. for (var i = 0; i < this._normals32.length; i++) {
  47786. this._fixedNormal32[i] = this._normals32[i];
  47787. }
  47788. }
  47789. if (!this.mesh.areNormalsFrozen) {
  47790. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  47791. }
  47792. }
  47793. if (this._depthSort && this._depthSortParticles) {
  47794. this.depthSortedParticles.sort(this._depthSortFunction);
  47795. var dspl = this.depthSortedParticles.length;
  47796. var sorted = 0;
  47797. var lind = 0;
  47798. var sind = 0;
  47799. var sid = 0;
  47800. for (sorted = 0; sorted < dspl; sorted++) {
  47801. lind = this.depthSortedParticles[sorted].indicesLength;
  47802. sind = this.depthSortedParticles[sorted].ind;
  47803. for (var i = 0; i < lind; i++) {
  47804. this._indices32[sid] = this._indices[sind + i];
  47805. sid++;
  47806. }
  47807. }
  47808. this.mesh.updateIndices(this._indices32);
  47809. }
  47810. }
  47811. if (this._computeBoundingBox) {
  47812. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  47813. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  47814. }
  47815. this.afterUpdateParticles(start, end, update);
  47816. return this;
  47817. };
  47818. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  47819. this._halfroll = this._roll * 0.5;
  47820. this._halfpitch = this._pitch * 0.5;
  47821. this._halfyaw = this._yaw * 0.5;
  47822. this._sinRoll = Math.sin(this._halfroll);
  47823. this._cosRoll = Math.cos(this._halfroll);
  47824. this._sinPitch = Math.sin(this._halfpitch);
  47825. this._cosPitch = Math.cos(this._halfpitch);
  47826. this._sinYaw = Math.sin(this._halfyaw);
  47827. this._cosYaw = Math.cos(this._halfyaw);
  47828. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  47829. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  47830. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  47831. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  47832. };
  47833. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  47834. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  47835. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  47836. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  47837. this._rotMatrix.m[3] = 0;
  47838. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  47839. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  47840. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  47841. this._rotMatrix.m[7] = 0;
  47842. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  47843. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  47844. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  47845. this._rotMatrix.m[11] = 0;
  47846. this._rotMatrix.m[12] = 0;
  47847. this._rotMatrix.m[13] = 0;
  47848. this._rotMatrix.m[14] = 0;
  47849. this._rotMatrix.m[15] = 1.0;
  47850. };
  47851. /**
  47852. * Disposes the SPS.
  47853. * Returns nothing.
  47854. */
  47855. SolidParticleSystem.prototype.dispose = function () {
  47856. this.mesh.dispose();
  47857. this.vars = null;
  47858. // drop references to internal big arrays for the GC
  47859. this._positions = null;
  47860. this._indices = null;
  47861. this._normals = null;
  47862. this._uvs = null;
  47863. this._colors = null;
  47864. this._indices32 = null;
  47865. this._positions32 = null;
  47866. this._normals32 = null;
  47867. this._fixedNormal32 = null;
  47868. this._uvs32 = null;
  47869. this._colors32 = null;
  47870. this.pickedParticles = null;
  47871. };
  47872. /**
  47873. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  47874. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47875. * Returns the SPS.
  47876. */
  47877. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  47878. if (!this._isVisibilityBoxLocked) {
  47879. this.mesh.refreshBoundingInfo();
  47880. }
  47881. return this;
  47882. };
  47883. /**
  47884. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  47885. * @param size the size (float) of the visibility box
  47886. * note : this doesn't lock the SPS mesh bounding box.
  47887. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47888. */
  47889. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  47890. var vis = size / 2;
  47891. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  47892. };
  47893. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  47894. // getter and setter
  47895. get: function () {
  47896. return this._alwaysVisible;
  47897. },
  47898. /**
  47899. * Sets the SPS as always visible or not
  47900. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47901. */
  47902. set: function (val) {
  47903. this._alwaysVisible = val;
  47904. this.mesh.alwaysSelectAsActiveMesh = val;
  47905. },
  47906. enumerable: true,
  47907. configurable: true
  47908. });
  47909. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  47910. get: function () {
  47911. return this._isVisibilityBoxLocked;
  47912. },
  47913. /**
  47914. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  47915. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47916. */
  47917. set: function (val) {
  47918. this._isVisibilityBoxLocked = val;
  47919. var boundingInfo = this.mesh.getBoundingInfo();
  47920. boundingInfo.isLocked = val;
  47921. },
  47922. enumerable: true,
  47923. configurable: true
  47924. });
  47925. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  47926. // getters
  47927. get: function () {
  47928. return this._computeParticleRotation;
  47929. },
  47930. // Optimizer setters
  47931. /**
  47932. * Tells to `setParticles()` to compute the particle rotations or not.
  47933. * Default value : true. The SPS is faster when it's set to false.
  47934. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  47935. */
  47936. set: function (val) {
  47937. this._computeParticleRotation = val;
  47938. },
  47939. enumerable: true,
  47940. configurable: true
  47941. });
  47942. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  47943. get: function () {
  47944. return this._computeParticleColor;
  47945. },
  47946. /**
  47947. * Tells to `setParticles()` to compute the particle colors or not.
  47948. * Default value : true. The SPS is faster when it's set to false.
  47949. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  47950. */
  47951. set: function (val) {
  47952. this._computeParticleColor = val;
  47953. },
  47954. enumerable: true,
  47955. configurable: true
  47956. });
  47957. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  47958. get: function () {
  47959. return this._computeParticleTexture;
  47960. },
  47961. /**
  47962. * Tells to `setParticles()` to compute the particle textures or not.
  47963. * Default value : true. The SPS is faster when it's set to false.
  47964. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  47965. */
  47966. set: function (val) {
  47967. this._computeParticleTexture = val;
  47968. },
  47969. enumerable: true,
  47970. configurable: true
  47971. });
  47972. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  47973. get: function () {
  47974. return this._computeParticleVertex;
  47975. },
  47976. /**
  47977. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  47978. * Default value : false. The SPS is faster when it's set to false.
  47979. * Note : the particle custom vertex positions aren't stored values.
  47980. */
  47981. set: function (val) {
  47982. this._computeParticleVertex = val;
  47983. },
  47984. enumerable: true,
  47985. configurable: true
  47986. });
  47987. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  47988. get: function () {
  47989. return this._computeBoundingBox;
  47990. },
  47991. /**
  47992. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  47993. */
  47994. set: function (val) {
  47995. this._computeBoundingBox = val;
  47996. },
  47997. enumerable: true,
  47998. configurable: true
  47999. });
  48000. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  48001. get: function () {
  48002. return this._depthSortParticles;
  48003. },
  48004. /**
  48005. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  48006. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  48007. * Default : `true`
  48008. */
  48009. set: function (val) {
  48010. this._depthSortParticles = val;
  48011. },
  48012. enumerable: true,
  48013. configurable: true
  48014. });
  48015. // =======================================================================
  48016. // Particle behavior logic
  48017. // these following methods may be overwritten by the user to fit his needs
  48018. /**
  48019. * This function does nothing. It may be overwritten to set all the particle first values.
  48020. * The SPS doesn't call this function, you may have to call it by your own.
  48021. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48022. */
  48023. SolidParticleSystem.prototype.initParticles = function () {
  48024. };
  48025. /**
  48026. * This function does nothing. It may be overwritten to recycle a particle.
  48027. * The SPS doesn't call this function, you may have to call it by your own.
  48028. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48029. */
  48030. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  48031. return particle;
  48032. };
  48033. /**
  48034. * Updates a particle : this function should be overwritten by the user.
  48035. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  48036. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48037. * ex : just set a particle position or velocity and recycle conditions
  48038. */
  48039. SolidParticleSystem.prototype.updateParticle = function (particle) {
  48040. return particle;
  48041. };
  48042. /**
  48043. * Updates a vertex of a particle : it can be overwritten by the user.
  48044. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  48045. * @param particle the current particle
  48046. * @param vertex the current index of the current particle
  48047. * @param pt the index of the current vertex in the particle shape
  48048. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  48049. * ex : just set a vertex particle position
  48050. */
  48051. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  48052. return vertex;
  48053. };
  48054. /**
  48055. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  48056. * This does nothing and may be overwritten by the user.
  48057. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48058. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48059. * @param update the boolean update value actually passed to setParticles()
  48060. */
  48061. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  48062. };
  48063. /**
  48064. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  48065. * This will be passed three parameters.
  48066. * This does nothing and may be overwritten by the user.
  48067. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48068. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48069. * @param update the boolean update value actually passed to setParticles()
  48070. */
  48071. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  48072. };
  48073. return SolidParticleSystem;
  48074. }());
  48075. BABYLON.SolidParticleSystem = SolidParticleSystem;
  48076. })(BABYLON || (BABYLON = {}));
  48077. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  48078. var BABYLON;
  48079. (function (BABYLON) {
  48080. var ShaderMaterial = /** @class */ (function (_super) {
  48081. __extends(ShaderMaterial, _super);
  48082. function ShaderMaterial(name, scene, shaderPath, options) {
  48083. var _this = _super.call(this, name, scene) || this;
  48084. _this._textures = {};
  48085. _this._textureArrays = {};
  48086. _this._floats = {};
  48087. _this._ints = {};
  48088. _this._floatsArrays = {};
  48089. _this._colors3 = {};
  48090. _this._colors3Arrays = {};
  48091. _this._colors4 = {};
  48092. _this._vectors2 = {};
  48093. _this._vectors3 = {};
  48094. _this._vectors4 = {};
  48095. _this._matrices = {};
  48096. _this._matrices3x3 = {};
  48097. _this._matrices2x2 = {};
  48098. _this._vectors2Arrays = {};
  48099. _this._vectors3Arrays = {};
  48100. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  48101. _this._shaderPath = shaderPath;
  48102. options.needAlphaBlending = options.needAlphaBlending || false;
  48103. options.needAlphaTesting = options.needAlphaTesting || false;
  48104. options.attributes = options.attributes || ["position", "normal", "uv"];
  48105. options.uniforms = options.uniforms || ["worldViewProjection"];
  48106. options.uniformBuffers = options.uniformBuffers || [];
  48107. options.samplers = options.samplers || [];
  48108. options.defines = options.defines || [];
  48109. _this._options = options;
  48110. return _this;
  48111. }
  48112. ShaderMaterial.prototype.getClassName = function () {
  48113. return "ShaderMaterial";
  48114. };
  48115. ShaderMaterial.prototype.needAlphaBlending = function () {
  48116. return this._options.needAlphaBlending;
  48117. };
  48118. ShaderMaterial.prototype.needAlphaTesting = function () {
  48119. return this._options.needAlphaTesting;
  48120. };
  48121. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  48122. if (this._options.uniforms.indexOf(uniformName) === -1) {
  48123. this._options.uniforms.push(uniformName);
  48124. }
  48125. };
  48126. ShaderMaterial.prototype.setTexture = function (name, texture) {
  48127. if (this._options.samplers.indexOf(name) === -1) {
  48128. this._options.samplers.push(name);
  48129. }
  48130. this._textures[name] = texture;
  48131. return this;
  48132. };
  48133. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  48134. if (this._options.samplers.indexOf(name) === -1) {
  48135. this._options.samplers.push(name);
  48136. }
  48137. this._checkUniform(name);
  48138. this._textureArrays[name] = textures;
  48139. return this;
  48140. };
  48141. ShaderMaterial.prototype.setFloat = function (name, value) {
  48142. this._checkUniform(name);
  48143. this._floats[name] = value;
  48144. return this;
  48145. };
  48146. ShaderMaterial.prototype.setInt = function (name, value) {
  48147. this._checkUniform(name);
  48148. this._ints[name] = value;
  48149. return this;
  48150. };
  48151. ShaderMaterial.prototype.setFloats = function (name, value) {
  48152. this._checkUniform(name);
  48153. this._floatsArrays[name] = value;
  48154. return this;
  48155. };
  48156. ShaderMaterial.prototype.setColor3 = function (name, value) {
  48157. this._checkUniform(name);
  48158. this._colors3[name] = value;
  48159. return this;
  48160. };
  48161. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  48162. this._checkUniform(name);
  48163. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  48164. color.toArray(arr, arr.length);
  48165. return arr;
  48166. }, []);
  48167. return this;
  48168. };
  48169. ShaderMaterial.prototype.setColor4 = function (name, value) {
  48170. this._checkUniform(name);
  48171. this._colors4[name] = value;
  48172. return this;
  48173. };
  48174. ShaderMaterial.prototype.setVector2 = function (name, value) {
  48175. this._checkUniform(name);
  48176. this._vectors2[name] = value;
  48177. return this;
  48178. };
  48179. ShaderMaterial.prototype.setVector3 = function (name, value) {
  48180. this._checkUniform(name);
  48181. this._vectors3[name] = value;
  48182. return this;
  48183. };
  48184. ShaderMaterial.prototype.setVector4 = function (name, value) {
  48185. this._checkUniform(name);
  48186. this._vectors4[name] = value;
  48187. return this;
  48188. };
  48189. ShaderMaterial.prototype.setMatrix = function (name, value) {
  48190. this._checkUniform(name);
  48191. this._matrices[name] = value;
  48192. return this;
  48193. };
  48194. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  48195. this._checkUniform(name);
  48196. this._matrices3x3[name] = value;
  48197. return this;
  48198. };
  48199. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  48200. this._checkUniform(name);
  48201. this._matrices2x2[name] = value;
  48202. return this;
  48203. };
  48204. ShaderMaterial.prototype.setArray2 = function (name, value) {
  48205. this._checkUniform(name);
  48206. this._vectors2Arrays[name] = value;
  48207. return this;
  48208. };
  48209. ShaderMaterial.prototype.setArray3 = function (name, value) {
  48210. this._checkUniform(name);
  48211. this._vectors3Arrays[name] = value;
  48212. return this;
  48213. };
  48214. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  48215. if (!mesh) {
  48216. return true;
  48217. }
  48218. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  48219. return false;
  48220. }
  48221. return false;
  48222. };
  48223. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  48224. var scene = this.getScene();
  48225. var engine = scene.getEngine();
  48226. if (!this.checkReadyOnEveryCall) {
  48227. if (this._renderId === scene.getRenderId()) {
  48228. if (this._checkCache(scene, mesh, useInstances)) {
  48229. return true;
  48230. }
  48231. }
  48232. }
  48233. // Instances
  48234. var defines = [];
  48235. var attribs = [];
  48236. var fallbacks = new BABYLON.EffectFallbacks();
  48237. if (useInstances) {
  48238. defines.push("#define INSTANCES");
  48239. }
  48240. for (var index = 0; index < this._options.defines.length; index++) {
  48241. defines.push(this._options.defines[index]);
  48242. }
  48243. for (var index = 0; index < this._options.attributes.length; index++) {
  48244. attribs.push(this._options.attributes[index]);
  48245. }
  48246. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  48247. attribs.push(BABYLON.VertexBuffer.ColorKind);
  48248. defines.push("#define VERTEXCOLOR");
  48249. }
  48250. // Bones
  48251. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  48252. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48253. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48254. if (mesh.numBoneInfluencers > 4) {
  48255. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48256. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48257. }
  48258. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48259. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48260. fallbacks.addCPUSkinningFallback(0, mesh);
  48261. if (this._options.uniforms.indexOf("mBones") === -1) {
  48262. this._options.uniforms.push("mBones");
  48263. }
  48264. }
  48265. else {
  48266. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48267. }
  48268. // Textures
  48269. for (var name in this._textures) {
  48270. if (!this._textures[name].isReady()) {
  48271. return false;
  48272. }
  48273. }
  48274. // Alpha test
  48275. if (engine.getAlphaTesting()) {
  48276. defines.push("#define ALPHATEST");
  48277. }
  48278. var previousEffect = this._effect;
  48279. var join = defines.join("\n");
  48280. this._effect = engine.createEffect(this._shaderPath, {
  48281. attributes: attribs,
  48282. uniformsNames: this._options.uniforms,
  48283. uniformBuffersNames: this._options.uniformBuffers,
  48284. samplers: this._options.samplers,
  48285. defines: join,
  48286. fallbacks: fallbacks,
  48287. onCompiled: this.onCompiled,
  48288. onError: this.onError
  48289. }, engine);
  48290. if (!this._effect.isReady()) {
  48291. return false;
  48292. }
  48293. if (previousEffect !== this._effect) {
  48294. scene.resetCachedMaterial();
  48295. }
  48296. this._renderId = scene.getRenderId();
  48297. return true;
  48298. };
  48299. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  48300. var scene = this.getScene();
  48301. if (!this._effect) {
  48302. return;
  48303. }
  48304. if (this._options.uniforms.indexOf("world") !== -1) {
  48305. this._effect.setMatrix("world", world);
  48306. }
  48307. if (this._options.uniforms.indexOf("worldView") !== -1) {
  48308. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  48309. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  48310. }
  48311. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  48312. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  48313. }
  48314. };
  48315. ShaderMaterial.prototype.bind = function (world, mesh) {
  48316. // Std values
  48317. this.bindOnlyWorldMatrix(world);
  48318. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  48319. if (this._options.uniforms.indexOf("view") !== -1) {
  48320. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  48321. }
  48322. if (this._options.uniforms.indexOf("projection") !== -1) {
  48323. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  48324. }
  48325. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  48326. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  48327. }
  48328. // Bones
  48329. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  48330. var name;
  48331. // Texture
  48332. for (name in this._textures) {
  48333. this._effect.setTexture(name, this._textures[name]);
  48334. }
  48335. // Texture arrays
  48336. for (name in this._textureArrays) {
  48337. this._effect.setTextureArray(name, this._textureArrays[name]);
  48338. }
  48339. // Int
  48340. for (name in this._ints) {
  48341. this._effect.setInt(name, this._ints[name]);
  48342. }
  48343. // Float
  48344. for (name in this._floats) {
  48345. this._effect.setFloat(name, this._floats[name]);
  48346. }
  48347. // Floats
  48348. for (name in this._floatsArrays) {
  48349. this._effect.setArray(name, this._floatsArrays[name]);
  48350. }
  48351. // Color3
  48352. for (name in this._colors3) {
  48353. this._effect.setColor3(name, this._colors3[name]);
  48354. }
  48355. for (name in this._colors3Arrays) {
  48356. this._effect.setArray3(name, this._colors3Arrays[name]);
  48357. }
  48358. // Color4
  48359. for (name in this._colors4) {
  48360. var color = this._colors4[name];
  48361. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  48362. }
  48363. // Vector2
  48364. for (name in this._vectors2) {
  48365. this._effect.setVector2(name, this._vectors2[name]);
  48366. }
  48367. // Vector3
  48368. for (name in this._vectors3) {
  48369. this._effect.setVector3(name, this._vectors3[name]);
  48370. }
  48371. // Vector4
  48372. for (name in this._vectors4) {
  48373. this._effect.setVector4(name, this._vectors4[name]);
  48374. }
  48375. // Matrix
  48376. for (name in this._matrices) {
  48377. this._effect.setMatrix(name, this._matrices[name]);
  48378. }
  48379. // Matrix 3x3
  48380. for (name in this._matrices3x3) {
  48381. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  48382. }
  48383. // Matrix 2x2
  48384. for (name in this._matrices2x2) {
  48385. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  48386. }
  48387. // Vector2Array
  48388. for (name in this._vectors2Arrays) {
  48389. this._effect.setArray2(name, this._vectors2Arrays[name]);
  48390. }
  48391. // Vector3Array
  48392. for (name in this._vectors3Arrays) {
  48393. this._effect.setArray3(name, this._vectors3Arrays[name]);
  48394. }
  48395. }
  48396. this._afterBind(mesh);
  48397. };
  48398. ShaderMaterial.prototype.getActiveTextures = function () {
  48399. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48400. for (var name in this._textures) {
  48401. activeTextures.push(this._textures[name]);
  48402. }
  48403. for (var name in this._textureArrays) {
  48404. var array = this._textureArrays[name];
  48405. for (var index = 0; index < array.length; index++) {
  48406. activeTextures.push(array[index]);
  48407. }
  48408. }
  48409. return activeTextures;
  48410. };
  48411. ShaderMaterial.prototype.hasTexture = function (texture) {
  48412. if (_super.prototype.hasTexture.call(this, texture)) {
  48413. return true;
  48414. }
  48415. for (var name in this._textures) {
  48416. if (this._textures[name] === texture) {
  48417. return true;
  48418. }
  48419. }
  48420. for (var name in this._textureArrays) {
  48421. var array = this._textureArrays[name];
  48422. for (var index = 0; index < array.length; index++) {
  48423. if (array[index] === texture) {
  48424. return true;
  48425. }
  48426. }
  48427. }
  48428. return false;
  48429. };
  48430. ShaderMaterial.prototype.clone = function (name) {
  48431. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  48432. return newShaderMaterial;
  48433. };
  48434. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48435. if (forceDisposeTextures) {
  48436. var name;
  48437. for (name in this._textures) {
  48438. this._textures[name].dispose();
  48439. }
  48440. for (name in this._textureArrays) {
  48441. var array = this._textureArrays[name];
  48442. for (var index = 0; index < array.length; index++) {
  48443. array[index].dispose();
  48444. }
  48445. }
  48446. }
  48447. this._textures = {};
  48448. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48449. };
  48450. ShaderMaterial.prototype.serialize = function () {
  48451. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48452. serializationObject.customType = "BABYLON.ShaderMaterial";
  48453. serializationObject.options = this._options;
  48454. serializationObject.shaderPath = this._shaderPath;
  48455. var name;
  48456. // Texture
  48457. serializationObject.textures = {};
  48458. for (name in this._textures) {
  48459. serializationObject.textures[name] = this._textures[name].serialize();
  48460. }
  48461. // Texture arrays
  48462. serializationObject.textureArrays = {};
  48463. for (name in this._textureArrays) {
  48464. serializationObject.textureArrays[name] = [];
  48465. var array = this._textureArrays[name];
  48466. for (var index = 0; index < array.length; index++) {
  48467. serializationObject.textureArrays[name].push(array[index].serialize());
  48468. }
  48469. }
  48470. // Float
  48471. serializationObject.floats = {};
  48472. for (name in this._floats) {
  48473. serializationObject.floats[name] = this._floats[name];
  48474. }
  48475. // Float s
  48476. serializationObject.FloatArrays = {};
  48477. for (name in this._floatsArrays) {
  48478. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  48479. }
  48480. // Color3
  48481. serializationObject.colors3 = {};
  48482. for (name in this._colors3) {
  48483. serializationObject.colors3[name] = this._colors3[name].asArray();
  48484. }
  48485. // Color3 array
  48486. serializationObject.colors3Arrays = {};
  48487. for (name in this._colors3Arrays) {
  48488. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  48489. }
  48490. // Color4
  48491. serializationObject.colors4 = {};
  48492. for (name in this._colors4) {
  48493. serializationObject.colors4[name] = this._colors4[name].asArray();
  48494. }
  48495. // Vector2
  48496. serializationObject.vectors2 = {};
  48497. for (name in this._vectors2) {
  48498. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  48499. }
  48500. // Vector3
  48501. serializationObject.vectors3 = {};
  48502. for (name in this._vectors3) {
  48503. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  48504. }
  48505. // Vector4
  48506. serializationObject.vectors4 = {};
  48507. for (name in this._vectors4) {
  48508. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  48509. }
  48510. // Matrix
  48511. serializationObject.matrices = {};
  48512. for (name in this._matrices) {
  48513. serializationObject.matrices[name] = this._matrices[name].asArray();
  48514. }
  48515. // Matrix 3x3
  48516. serializationObject.matrices3x3 = {};
  48517. for (name in this._matrices3x3) {
  48518. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  48519. }
  48520. // Matrix 2x2
  48521. serializationObject.matrices2x2 = {};
  48522. for (name in this._matrices2x2) {
  48523. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  48524. }
  48525. // Vector2Array
  48526. serializationObject.vectors2Arrays = {};
  48527. for (name in this._vectors2Arrays) {
  48528. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  48529. }
  48530. // Vector3Array
  48531. serializationObject.vectors3Arrays = {};
  48532. for (name in this._vectors3Arrays) {
  48533. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  48534. }
  48535. return serializationObject;
  48536. };
  48537. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  48538. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  48539. var name;
  48540. // Texture
  48541. for (name in source.textures) {
  48542. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  48543. }
  48544. // Texture arrays
  48545. for (name in source.textureArrays) {
  48546. var array = source.textureArrays[name];
  48547. var textureArray = new Array();
  48548. for (var index = 0; index < array.length; index++) {
  48549. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  48550. }
  48551. material.setTextureArray(name, textureArray);
  48552. }
  48553. // Float
  48554. for (name in source.floats) {
  48555. material.setFloat(name, source.floats[name]);
  48556. }
  48557. // Float s
  48558. for (name in source.floatsArrays) {
  48559. material.setFloats(name, source.floatsArrays[name]);
  48560. }
  48561. // Color3
  48562. for (name in source.colors3) {
  48563. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  48564. }
  48565. // Color3 arrays
  48566. for (name in source.colors3Arrays) {
  48567. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  48568. if (i % 3 === 0) {
  48569. arr.push([num]);
  48570. }
  48571. else {
  48572. arr[arr.length - 1].push(num);
  48573. }
  48574. return arr;
  48575. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  48576. material.setColor3Array(name, colors);
  48577. }
  48578. // Color4
  48579. for (name in source.colors4) {
  48580. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  48581. }
  48582. // Vector2
  48583. for (name in source.vectors2) {
  48584. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  48585. }
  48586. // Vector3
  48587. for (name in source.vectors3) {
  48588. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  48589. }
  48590. // Vector4
  48591. for (name in source.vectors4) {
  48592. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  48593. }
  48594. // Matrix
  48595. for (name in source.matrices) {
  48596. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  48597. }
  48598. // Matrix 3x3
  48599. for (name in source.matrices3x3) {
  48600. material.setMatrix3x3(name, source.matrices3x3[name]);
  48601. }
  48602. // Matrix 2x2
  48603. for (name in source.matrices2x2) {
  48604. material.setMatrix2x2(name, source.matrices2x2[name]);
  48605. }
  48606. // Vector2Array
  48607. for (name in source.vectors2Arrays) {
  48608. material.setArray2(name, source.vectors2Arrays[name]);
  48609. }
  48610. // Vector3Array
  48611. for (name in source.vectors3Arrays) {
  48612. material.setArray3(name, source.vectors3Arrays[name]);
  48613. }
  48614. return material;
  48615. };
  48616. return ShaderMaterial;
  48617. }(BABYLON.Material));
  48618. BABYLON.ShaderMaterial = ShaderMaterial;
  48619. })(BABYLON || (BABYLON = {}));
  48620. //# sourceMappingURL=babylon.shaderMaterial.js.map
  48621. var BABYLON;
  48622. (function (BABYLON) {
  48623. var GroundMesh = /** @class */ (function (_super) {
  48624. __extends(GroundMesh, _super);
  48625. function GroundMesh(name, scene) {
  48626. var _this = _super.call(this, name, scene) || this;
  48627. _this.generateOctree = false;
  48628. return _this;
  48629. }
  48630. GroundMesh.prototype.getClassName = function () {
  48631. return "GroundMesh";
  48632. };
  48633. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  48634. get: function () {
  48635. return Math.min(this._subdivisionsX, this._subdivisionsY);
  48636. },
  48637. enumerable: true,
  48638. configurable: true
  48639. });
  48640. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  48641. get: function () {
  48642. return this._subdivisionsX;
  48643. },
  48644. enumerable: true,
  48645. configurable: true
  48646. });
  48647. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  48648. get: function () {
  48649. return this._subdivisionsY;
  48650. },
  48651. enumerable: true,
  48652. configurable: true
  48653. });
  48654. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  48655. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  48656. this._subdivisionsX = chunksCount;
  48657. this._subdivisionsY = chunksCount;
  48658. this.subdivide(chunksCount);
  48659. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  48660. };
  48661. /**
  48662. * Returns a height (y) value in the Worl system :
  48663. * the ground altitude at the coordinates (x, z) expressed in the World system.
  48664. * Returns the ground y position if (x, z) are outside the ground surface.
  48665. */
  48666. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  48667. var world = this.getWorldMatrix();
  48668. var invMat = BABYLON.Tmp.Matrix[5];
  48669. world.invertToRef(invMat);
  48670. var tmpVect = BABYLON.Tmp.Vector3[8];
  48671. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  48672. x = tmpVect.x;
  48673. z = tmpVect.z;
  48674. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  48675. return this.position.y;
  48676. }
  48677. if (!this._heightQuads || this._heightQuads.length == 0) {
  48678. this._initHeightQuads();
  48679. this._computeHeightQuads();
  48680. }
  48681. var facet = this._getFacetAt(x, z);
  48682. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  48683. // return y in the World system
  48684. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  48685. return tmpVect.y;
  48686. };
  48687. /**
  48688. * Returns a normalized vector (Vector3) orthogonal to the ground
  48689. * at the ground coordinates (x, z) expressed in the World system.
  48690. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  48691. */
  48692. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  48693. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  48694. this.getNormalAtCoordinatesToRef(x, z, normal);
  48695. return normal;
  48696. };
  48697. /**
  48698. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  48699. * at the ground coordinates (x, z) expressed in the World system.
  48700. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  48701. * Returns the GroundMesh.
  48702. */
  48703. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  48704. var world = this.getWorldMatrix();
  48705. var tmpMat = BABYLON.Tmp.Matrix[5];
  48706. world.invertToRef(tmpMat);
  48707. var tmpVect = BABYLON.Tmp.Vector3[8];
  48708. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  48709. x = tmpVect.x;
  48710. z = tmpVect.z;
  48711. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  48712. return this;
  48713. }
  48714. if (!this._heightQuads || this._heightQuads.length == 0) {
  48715. this._initHeightQuads();
  48716. this._computeHeightQuads();
  48717. }
  48718. var facet = this._getFacetAt(x, z);
  48719. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  48720. return this;
  48721. };
  48722. /**
  48723. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  48724. * if the ground has been updated.
  48725. * This can be used in the render loop.
  48726. * Returns the GroundMesh.
  48727. */
  48728. GroundMesh.prototype.updateCoordinateHeights = function () {
  48729. if (!this._heightQuads || this._heightQuads.length == 0) {
  48730. this._initHeightQuads();
  48731. }
  48732. this._computeHeightQuads();
  48733. return this;
  48734. };
  48735. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  48736. GroundMesh.prototype._getFacetAt = function (x, z) {
  48737. // retrieve col and row from x, z coordinates in the ground local system
  48738. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  48739. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  48740. var quad = this._heightQuads[row * this._subdivisionsX + col];
  48741. var facet;
  48742. if (z < quad.slope.x * x + quad.slope.y) {
  48743. facet = quad.facet1;
  48744. }
  48745. else {
  48746. facet = quad.facet2;
  48747. }
  48748. return facet;
  48749. };
  48750. // Creates and populates the heightMap array with "facet" elements :
  48751. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  48752. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  48753. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  48754. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  48755. // Returns the GroundMesh.
  48756. GroundMesh.prototype._initHeightQuads = function () {
  48757. var subdivisionsX = this._subdivisionsX;
  48758. var subdivisionsY = this._subdivisionsY;
  48759. this._heightQuads = new Array();
  48760. for (var row = 0; row < subdivisionsY; row++) {
  48761. for (var col = 0; col < subdivisionsX; col++) {
  48762. 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) };
  48763. this._heightQuads[row * subdivisionsX + col] = quad;
  48764. }
  48765. }
  48766. return this;
  48767. };
  48768. // Compute each quad element values and update the the heightMap array :
  48769. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  48770. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  48771. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  48772. // Returns the GroundMesh.
  48773. GroundMesh.prototype._computeHeightQuads = function () {
  48774. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48775. if (!positions) {
  48776. return this;
  48777. }
  48778. var v1 = BABYLON.Tmp.Vector3[3];
  48779. var v2 = BABYLON.Tmp.Vector3[2];
  48780. var v3 = BABYLON.Tmp.Vector3[1];
  48781. var v4 = BABYLON.Tmp.Vector3[0];
  48782. var v1v2 = BABYLON.Tmp.Vector3[4];
  48783. var v1v3 = BABYLON.Tmp.Vector3[5];
  48784. var v1v4 = BABYLON.Tmp.Vector3[6];
  48785. var norm1 = BABYLON.Tmp.Vector3[7];
  48786. var norm2 = BABYLON.Tmp.Vector3[8];
  48787. var i = 0;
  48788. var j = 0;
  48789. var k = 0;
  48790. var cd = 0; // 2D slope coefficient : z = cd * x + h
  48791. var h = 0;
  48792. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  48793. var d2 = 0;
  48794. var subdivisionsX = this._subdivisionsX;
  48795. var subdivisionsY = this._subdivisionsY;
  48796. for (var row = 0; row < subdivisionsY; row++) {
  48797. for (var col = 0; col < subdivisionsX; col++) {
  48798. i = col * 3;
  48799. j = row * (subdivisionsX + 1) * 3;
  48800. k = (row + 1) * (subdivisionsX + 1) * 3;
  48801. v1.x = positions[j + i];
  48802. v1.y = positions[j + i + 1];
  48803. v1.z = positions[j + i + 2];
  48804. v2.x = positions[j + i + 3];
  48805. v2.y = positions[j + i + 4];
  48806. v2.z = positions[j + i + 5];
  48807. v3.x = positions[k + i];
  48808. v3.y = positions[k + i + 1];
  48809. v3.z = positions[k + i + 2];
  48810. v4.x = positions[k + i + 3];
  48811. v4.y = positions[k + i + 4];
  48812. v4.z = positions[k + i + 5];
  48813. // 2D slope V1V4
  48814. cd = (v4.z - v1.z) / (v4.x - v1.x);
  48815. h = v1.z - cd * v1.x; // v1 belongs to the slope
  48816. // facet equations :
  48817. // we compute each facet normal vector
  48818. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  48819. // we compute the value d by applying the equation to v1 which belongs to the plane
  48820. // then we store the facet equation in a Vector4
  48821. v2.subtractToRef(v1, v1v2);
  48822. v3.subtractToRef(v1, v1v3);
  48823. v4.subtractToRef(v1, v1v4);
  48824. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  48825. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  48826. norm1.normalize();
  48827. norm2.normalize();
  48828. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  48829. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  48830. var quad = this._heightQuads[row * subdivisionsX + col];
  48831. quad.slope.copyFromFloats(cd, h);
  48832. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  48833. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  48834. }
  48835. }
  48836. return this;
  48837. };
  48838. GroundMesh.prototype.serialize = function (serializationObject) {
  48839. _super.prototype.serialize.call(this, serializationObject);
  48840. serializationObject.subdivisionsX = this._subdivisionsX;
  48841. serializationObject.subdivisionsY = this._subdivisionsY;
  48842. serializationObject.minX = this._minX;
  48843. serializationObject.maxX = this._maxX;
  48844. serializationObject.minZ = this._minZ;
  48845. serializationObject.maxZ = this._maxZ;
  48846. serializationObject.width = this._width;
  48847. serializationObject.height = this._height;
  48848. };
  48849. GroundMesh.Parse = function (parsedMesh, scene) {
  48850. var result = new GroundMesh(parsedMesh.name, scene);
  48851. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  48852. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  48853. result._minX = parsedMesh.minX;
  48854. result._maxX = parsedMesh.maxX;
  48855. result._minZ = parsedMesh.minZ;
  48856. result._maxZ = parsedMesh.maxZ;
  48857. result._width = parsedMesh.width;
  48858. result._height = parsedMesh.height;
  48859. return result;
  48860. };
  48861. return GroundMesh;
  48862. }(BABYLON.Mesh));
  48863. BABYLON.GroundMesh = GroundMesh;
  48864. })(BABYLON || (BABYLON = {}));
  48865. //# sourceMappingURL=babylon.groundMesh.js.map
  48866. var BABYLON;
  48867. (function (BABYLON) {
  48868. /**
  48869. * Creates an instance based on a source mesh.
  48870. */
  48871. var InstancedMesh = /** @class */ (function (_super) {
  48872. __extends(InstancedMesh, _super);
  48873. function InstancedMesh(name, source) {
  48874. var _this = _super.call(this, name, source.getScene()) || this;
  48875. source.instances.push(_this);
  48876. _this._sourceMesh = source;
  48877. _this.position.copyFrom(source.position);
  48878. _this.rotation.copyFrom(source.rotation);
  48879. _this.scaling.copyFrom(source.scaling);
  48880. if (source.rotationQuaternion) {
  48881. _this.rotationQuaternion = source.rotationQuaternion.clone();
  48882. }
  48883. _this.infiniteDistance = source.infiniteDistance;
  48884. _this.setPivotMatrix(source.getPivotMatrix());
  48885. _this.refreshBoundingInfo();
  48886. _this._syncSubMeshes();
  48887. return _this;
  48888. }
  48889. /**
  48890. * Returns the string "InstancedMesh".
  48891. */
  48892. InstancedMesh.prototype.getClassName = function () {
  48893. return "InstancedMesh";
  48894. };
  48895. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  48896. // Methods
  48897. get: function () {
  48898. return this._sourceMesh.receiveShadows;
  48899. },
  48900. enumerable: true,
  48901. configurable: true
  48902. });
  48903. Object.defineProperty(InstancedMesh.prototype, "material", {
  48904. get: function () {
  48905. return this._sourceMesh.material;
  48906. },
  48907. enumerable: true,
  48908. configurable: true
  48909. });
  48910. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  48911. get: function () {
  48912. return this._sourceMesh.visibility;
  48913. },
  48914. enumerable: true,
  48915. configurable: true
  48916. });
  48917. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  48918. get: function () {
  48919. return this._sourceMesh.skeleton;
  48920. },
  48921. enumerable: true,
  48922. configurable: true
  48923. });
  48924. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  48925. get: function () {
  48926. return this._sourceMesh.renderingGroupId;
  48927. },
  48928. enumerable: true,
  48929. configurable: true
  48930. });
  48931. /**
  48932. * Returns the total number of vertices (integer).
  48933. */
  48934. InstancedMesh.prototype.getTotalVertices = function () {
  48935. return this._sourceMesh.getTotalVertices();
  48936. };
  48937. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  48938. get: function () {
  48939. return this._sourceMesh;
  48940. },
  48941. enumerable: true,
  48942. configurable: true
  48943. });
  48944. /**
  48945. * Is this node ready to be used/rendered
  48946. * @return {boolean} is it ready
  48947. */
  48948. InstancedMesh.prototype.isReady = function () {
  48949. return this._sourceMesh.isReady(true);
  48950. };
  48951. /**
  48952. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  48953. */
  48954. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  48955. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  48956. };
  48957. /**
  48958. * Sets the vertex data of the mesh geometry for the requested `kind`.
  48959. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  48960. * The `data` are either a numeric array either a Float32Array.
  48961. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  48962. * 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).
  48963. * Note that a new underlying VertexBuffer object is created each call.
  48964. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  48965. *
  48966. * Possible `kind` values :
  48967. * - BABYLON.VertexBuffer.PositionKind
  48968. * - BABYLON.VertexBuffer.UVKind
  48969. * - BABYLON.VertexBuffer.UV2Kind
  48970. * - BABYLON.VertexBuffer.UV3Kind
  48971. * - BABYLON.VertexBuffer.UV4Kind
  48972. * - BABYLON.VertexBuffer.UV5Kind
  48973. * - BABYLON.VertexBuffer.UV6Kind
  48974. * - BABYLON.VertexBuffer.ColorKind
  48975. * - BABYLON.VertexBuffer.MatricesIndicesKind
  48976. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  48977. * - BABYLON.VertexBuffer.MatricesWeightsKind
  48978. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  48979. *
  48980. * Returns the Mesh.
  48981. */
  48982. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  48983. if (this.sourceMesh) {
  48984. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  48985. }
  48986. return this.sourceMesh;
  48987. };
  48988. /**
  48989. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  48990. * If the mesh has no geometry, it is simply returned as it is.
  48991. * The `data` are either a numeric array either a Float32Array.
  48992. * No new underlying VertexBuffer object is created.
  48993. * 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.
  48994. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  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.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  49013. if (this.sourceMesh) {
  49014. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  49015. }
  49016. return this.sourceMesh;
  49017. };
  49018. /**
  49019. * Sets the mesh indices.
  49020. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  49021. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  49022. * This method creates a new index buffer each call.
  49023. * Returns the Mesh.
  49024. */
  49025. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  49026. if (totalVertices === void 0) { totalVertices = null; }
  49027. if (this.sourceMesh) {
  49028. this.sourceMesh.setIndices(indices, totalVertices);
  49029. }
  49030. return this.sourceMesh;
  49031. };
  49032. /**
  49033. * Boolean : True if the mesh owns the requested kind of data.
  49034. */
  49035. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  49036. return this._sourceMesh.isVerticesDataPresent(kind);
  49037. };
  49038. /**
  49039. * Returns an array of indices (IndicesArray).
  49040. */
  49041. InstancedMesh.prototype.getIndices = function () {
  49042. return this._sourceMesh.getIndices();
  49043. };
  49044. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  49045. get: function () {
  49046. return this._sourceMesh._positions;
  49047. },
  49048. enumerable: true,
  49049. configurable: true
  49050. });
  49051. /**
  49052. * Sets a new updated BoundingInfo to the mesh.
  49053. * Returns the mesh.
  49054. */
  49055. InstancedMesh.prototype.refreshBoundingInfo = function () {
  49056. var meshBB = this._sourceMesh.getBoundingInfo();
  49057. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  49058. this._updateBoundingInfo();
  49059. return this;
  49060. };
  49061. InstancedMesh.prototype._preActivate = function () {
  49062. if (this._currentLOD) {
  49063. this._currentLOD._preActivate();
  49064. }
  49065. return this;
  49066. };
  49067. InstancedMesh.prototype._activate = function (renderId) {
  49068. if (this._currentLOD) {
  49069. this._currentLOD._registerInstanceForRenderId(this, renderId);
  49070. }
  49071. return this;
  49072. };
  49073. /**
  49074. * Returns the current associated LOD AbstractMesh.
  49075. */
  49076. InstancedMesh.prototype.getLOD = function (camera) {
  49077. if (!camera) {
  49078. return this;
  49079. }
  49080. var boundingInfo = this.getBoundingInfo();
  49081. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  49082. if (this._currentLOD === this.sourceMesh) {
  49083. return this;
  49084. }
  49085. return this._currentLOD;
  49086. };
  49087. InstancedMesh.prototype._syncSubMeshes = function () {
  49088. this.releaseSubMeshes();
  49089. if (this._sourceMesh.subMeshes) {
  49090. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  49091. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  49092. }
  49093. }
  49094. return this;
  49095. };
  49096. InstancedMesh.prototype._generatePointsArray = function () {
  49097. return this._sourceMesh._generatePointsArray();
  49098. };
  49099. /**
  49100. * Creates a new InstancedMesh from the current mesh.
  49101. * - name (string) : the cloned mesh name
  49102. * - newParent (optional Node) : the optional Node to parent the clone to.
  49103. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  49104. *
  49105. * Returns the clone.
  49106. */
  49107. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  49108. var result = this._sourceMesh.createInstance(name);
  49109. // Deep copy
  49110. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  49111. // Bounding info
  49112. this.refreshBoundingInfo();
  49113. // Parent
  49114. if (newParent) {
  49115. result.parent = newParent;
  49116. }
  49117. if (!doNotCloneChildren) {
  49118. // Children
  49119. for (var index = 0; index < this.getScene().meshes.length; index++) {
  49120. var mesh = this.getScene().meshes[index];
  49121. if (mesh.parent === this) {
  49122. mesh.clone(mesh.name, result);
  49123. }
  49124. }
  49125. }
  49126. result.computeWorldMatrix(true);
  49127. return result;
  49128. };
  49129. /**
  49130. * Disposes the InstancedMesh.
  49131. * Returns nothing.
  49132. */
  49133. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  49134. // Remove from mesh
  49135. var index = this._sourceMesh.instances.indexOf(this);
  49136. this._sourceMesh.instances.splice(index, 1);
  49137. _super.prototype.dispose.call(this, doNotRecurse);
  49138. };
  49139. return InstancedMesh;
  49140. }(BABYLON.AbstractMesh));
  49141. BABYLON.InstancedMesh = InstancedMesh;
  49142. })(BABYLON || (BABYLON = {}));
  49143. //# sourceMappingURL=babylon.instancedMesh.js.map
  49144. var BABYLON;
  49145. (function (BABYLON) {
  49146. var LinesMesh = /** @class */ (function (_super) {
  49147. __extends(LinesMesh, _super);
  49148. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  49149. if (scene === void 0) { scene = null; }
  49150. if (parent === void 0) { parent = null; }
  49151. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  49152. _this.useVertexColor = useVertexColor;
  49153. _this.useVertexAlpha = useVertexAlpha;
  49154. _this.color = new BABYLON.Color3(1, 1, 1);
  49155. _this.alpha = 1;
  49156. if (source) {
  49157. _this.color = source.color.clone();
  49158. _this.alpha = source.alpha;
  49159. _this.useVertexColor = source.useVertexColor;
  49160. _this.useVertexAlpha = source.useVertexAlpha;
  49161. }
  49162. _this._intersectionThreshold = 0.1;
  49163. var defines = [];
  49164. var options = {
  49165. attributes: [BABYLON.VertexBuffer.PositionKind],
  49166. uniforms: ["world", "viewProjection"],
  49167. needAlphaBlending: true,
  49168. defines: defines
  49169. };
  49170. if (useVertexAlpha === false) {
  49171. options.needAlphaBlending = false;
  49172. }
  49173. if (!useVertexColor) {
  49174. options.uniforms.push("color");
  49175. }
  49176. else {
  49177. options.defines.push("#define VERTEXCOLOR");
  49178. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  49179. }
  49180. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  49181. return _this;
  49182. }
  49183. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  49184. /**
  49185. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  49186. * This margin is expressed in world space coordinates, so its value may vary.
  49187. * Default value is 0.1
  49188. * @returns the intersection Threshold value.
  49189. */
  49190. get: function () {
  49191. return this._intersectionThreshold;
  49192. },
  49193. /**
  49194. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  49195. * This margin is expressed in world space coordinates, so its value may vary.
  49196. * @param value the new threshold to apply
  49197. */
  49198. set: function (value) {
  49199. if (this._intersectionThreshold === value) {
  49200. return;
  49201. }
  49202. this._intersectionThreshold = value;
  49203. if (this.geometry) {
  49204. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  49205. }
  49206. },
  49207. enumerable: true,
  49208. configurable: true
  49209. });
  49210. /**
  49211. * Returns the string "LineMesh"
  49212. */
  49213. LinesMesh.prototype.getClassName = function () {
  49214. return "LinesMesh";
  49215. };
  49216. Object.defineProperty(LinesMesh.prototype, "material", {
  49217. get: function () {
  49218. return this._colorShader;
  49219. },
  49220. set: function (value) {
  49221. // Do nothing
  49222. },
  49223. enumerable: true,
  49224. configurable: true
  49225. });
  49226. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  49227. get: function () {
  49228. return false;
  49229. },
  49230. enumerable: true,
  49231. configurable: true
  49232. });
  49233. LinesMesh.prototype.createInstance = function (name) {
  49234. throw new Error("LinesMeshes do not support createInstance.");
  49235. };
  49236. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  49237. if (!this._geometry) {
  49238. return this;
  49239. }
  49240. // VBOs
  49241. this._geometry._bind(this._colorShader.getEffect());
  49242. // Color
  49243. if (!this.useVertexColor) {
  49244. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  49245. }
  49246. return this;
  49247. };
  49248. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  49249. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  49250. return this;
  49251. }
  49252. var engine = this.getScene().getEngine();
  49253. // Draw order
  49254. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  49255. return this;
  49256. };
  49257. LinesMesh.prototype.dispose = function (doNotRecurse) {
  49258. this._colorShader.dispose();
  49259. _super.prototype.dispose.call(this, doNotRecurse);
  49260. };
  49261. /**
  49262. * Returns a new LineMesh object cloned from the current one.
  49263. */
  49264. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  49265. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  49266. };
  49267. return LinesMesh;
  49268. }(BABYLON.Mesh));
  49269. BABYLON.LinesMesh = LinesMesh;
  49270. })(BABYLON || (BABYLON = {}));
  49271. //# sourceMappingURL=babylon.linesMesh.js.map
  49272. var BABYLON;
  49273. (function (BABYLON) {
  49274. var MeshBuilder = /** @class */ (function () {
  49275. function MeshBuilder() {
  49276. }
  49277. MeshBuilder.updateSideOrientation = function (orientation) {
  49278. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  49279. return BABYLON.Mesh.DOUBLESIDE;
  49280. }
  49281. if (orientation === undefined || orientation === null) {
  49282. return BABYLON.Mesh.FRONTSIDE;
  49283. }
  49284. return orientation;
  49285. };
  49286. /**
  49287. * Creates a box mesh.
  49288. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  49289. * The parameter `size` sets the size (float) of each box side (default 1).
  49290. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  49291. * 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).
  49292. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  49293. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49294. * 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).
  49295. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49296. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49297. */
  49298. MeshBuilder.CreateBox = function (name, options, scene) {
  49299. if (scene === void 0) { scene = null; }
  49300. var box = new BABYLON.Mesh(name, scene);
  49301. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49302. box._originalBuilderSideOrientation = options.sideOrientation;
  49303. var vertexData = BABYLON.VertexData.CreateBox(options);
  49304. vertexData.applyToMesh(box, options.updatable);
  49305. return box;
  49306. };
  49307. /**
  49308. * Creates a sphere mesh.
  49309. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  49310. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  49311. * 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`).
  49312. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  49313. * 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
  49314. * 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).
  49315. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49316. * 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).
  49317. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49318. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49319. */
  49320. MeshBuilder.CreateSphere = function (name, options, scene) {
  49321. var sphere = new BABYLON.Mesh(name, scene);
  49322. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49323. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49324. var vertexData = BABYLON.VertexData.CreateSphere(options);
  49325. vertexData.applyToMesh(sphere, options.updatable);
  49326. return sphere;
  49327. };
  49328. /**
  49329. * Creates a plane polygonal mesh. By default, this is a disc.
  49330. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  49331. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  49332. * 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.
  49333. * 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
  49334. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49335. * 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).
  49336. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49337. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49338. */
  49339. MeshBuilder.CreateDisc = function (name, options, scene) {
  49340. if (scene === void 0) { scene = null; }
  49341. var disc = new BABYLON.Mesh(name, scene);
  49342. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49343. disc._originalBuilderSideOrientation = options.sideOrientation;
  49344. var vertexData = BABYLON.VertexData.CreateDisc(options);
  49345. vertexData.applyToMesh(disc, options.updatable);
  49346. return disc;
  49347. };
  49348. /**
  49349. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  49350. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  49351. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  49352. * 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`).
  49353. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  49354. * 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.
  49355. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49356. * 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).
  49357. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49358. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49359. */
  49360. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  49361. var sphere = new BABYLON.Mesh(name, scene);
  49362. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49363. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49364. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  49365. vertexData.applyToMesh(sphere, options.updatable);
  49366. return sphere;
  49367. };
  49368. ;
  49369. /**
  49370. * Creates a ribbon mesh.
  49371. * 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.
  49372. *
  49373. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  49374. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  49375. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  49376. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  49377. * 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.
  49378. * 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.
  49379. * 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
  49380. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49381. * 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).
  49382. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49383. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49384. * 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.
  49385. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  49386. * 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
  49387. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  49388. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  49389. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49390. */
  49391. MeshBuilder.CreateRibbon = function (name, options, scene) {
  49392. if (scene === void 0) { scene = null; }
  49393. var pathArray = options.pathArray;
  49394. var closeArray = options.closeArray;
  49395. var closePath = options.closePath;
  49396. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49397. var instance = options.instance;
  49398. var updatable = options.updatable;
  49399. if (instance) {
  49400. // positionFunction : ribbon case
  49401. // only pathArray and sideOrientation parameters are taken into account for positions update
  49402. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  49403. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  49404. var positionFunction = function (positions) {
  49405. var minlg = pathArray[0].length;
  49406. var i = 0;
  49407. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  49408. for (var si = 1; si <= ns; si++) {
  49409. for (var p = 0; p < pathArray.length; p++) {
  49410. var path = pathArray[p];
  49411. var l = path.length;
  49412. minlg = (minlg < l) ? minlg : l;
  49413. var j = 0;
  49414. while (j < minlg) {
  49415. positions[i] = path[j].x;
  49416. positions[i + 1] = path[j].y;
  49417. positions[i + 2] = path[j].z;
  49418. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  49419. BABYLON.Tmp.Vector3[0].x = path[j].x;
  49420. }
  49421. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  49422. BABYLON.Tmp.Vector3[1].x = path[j].x;
  49423. }
  49424. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  49425. BABYLON.Tmp.Vector3[0].y = path[j].y;
  49426. }
  49427. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  49428. BABYLON.Tmp.Vector3[1].y = path[j].y;
  49429. }
  49430. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  49431. BABYLON.Tmp.Vector3[0].z = path[j].z;
  49432. }
  49433. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  49434. BABYLON.Tmp.Vector3[1].z = path[j].z;
  49435. }
  49436. j++;
  49437. i += 3;
  49438. }
  49439. if (instance._closePath) {
  49440. positions[i] = path[0].x;
  49441. positions[i + 1] = path[0].y;
  49442. positions[i + 2] = path[0].z;
  49443. i += 3;
  49444. }
  49445. }
  49446. }
  49447. };
  49448. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49449. positionFunction(positions);
  49450. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  49451. instance._boundingInfo.update(instance._worldMatrix);
  49452. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49453. if (options.colors) {
  49454. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49455. for (var c = 0; c < options.colors.length; c++) {
  49456. colors[c * 4] = options.colors[c].r;
  49457. colors[c * 4 + 1] = options.colors[c].g;
  49458. colors[c * 4 + 2] = options.colors[c].b;
  49459. colors[c * 4 + 3] = options.colors[c].a;
  49460. }
  49461. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  49462. }
  49463. if (options.uvs) {
  49464. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49465. for (var i = 0; i < options.uvs.length; i++) {
  49466. uvs[i * 2] = options.uvs[i].x;
  49467. uvs[i * 2 + 1] = options.uvs[i].y;
  49468. }
  49469. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  49470. }
  49471. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  49472. var indices = instance.getIndices();
  49473. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49474. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  49475. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  49476. if (instance._closePath) {
  49477. var indexFirst = 0;
  49478. var indexLast = 0;
  49479. for (var p = 0; p < pathArray.length; p++) {
  49480. indexFirst = instance._idx[p] * 3;
  49481. if (p + 1 < pathArray.length) {
  49482. indexLast = (instance._idx[p + 1] - 1) * 3;
  49483. }
  49484. else {
  49485. indexLast = normals.length - 3;
  49486. }
  49487. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  49488. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  49489. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  49490. normals[indexLast] = normals[indexFirst];
  49491. normals[indexLast + 1] = normals[indexFirst + 1];
  49492. normals[indexLast + 2] = normals[indexFirst + 2];
  49493. }
  49494. }
  49495. if (!(instance.areNormalsFrozen)) {
  49496. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  49497. }
  49498. }
  49499. return instance;
  49500. }
  49501. else {
  49502. var ribbon = new BABYLON.Mesh(name, scene);
  49503. ribbon._originalBuilderSideOrientation = sideOrientation;
  49504. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  49505. if (closePath) {
  49506. ribbon._idx = vertexData._idx;
  49507. }
  49508. ribbon._closePath = closePath;
  49509. ribbon._closeArray = closeArray;
  49510. vertexData.applyToMesh(ribbon, updatable);
  49511. return ribbon;
  49512. }
  49513. };
  49514. /**
  49515. * Creates a cylinder or a cone mesh.
  49516. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  49517. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  49518. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  49519. * 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.
  49520. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  49521. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  49522. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  49523. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  49524. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  49525. * 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).
  49526. * 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
  49527. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  49528. * 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
  49529. * 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.
  49530. * If `enclose` is false, a ring surface is one element.
  49531. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  49532. * 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
  49533. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49534. * 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).
  49535. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49536. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49537. */
  49538. MeshBuilder.CreateCylinder = function (name, options, scene) {
  49539. var cylinder = new BABYLON.Mesh(name, scene);
  49540. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49541. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  49542. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  49543. vertexData.applyToMesh(cylinder, options.updatable);
  49544. return cylinder;
  49545. };
  49546. /**
  49547. * Creates a torus mesh.
  49548. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  49549. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  49550. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  49551. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  49552. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49553. * 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).
  49554. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49555. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49556. */
  49557. MeshBuilder.CreateTorus = function (name, options, scene) {
  49558. var torus = new BABYLON.Mesh(name, scene);
  49559. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49560. torus._originalBuilderSideOrientation = options.sideOrientation;
  49561. var vertexData = BABYLON.VertexData.CreateTorus(options);
  49562. vertexData.applyToMesh(torus, options.updatable);
  49563. return torus;
  49564. };
  49565. /**
  49566. * Creates a torus knot mesh.
  49567. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  49568. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  49569. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  49570. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  49571. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  49572. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49573. * 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).
  49574. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49575. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49576. */
  49577. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  49578. var torusKnot = new BABYLON.Mesh(name, scene);
  49579. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49580. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  49581. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  49582. vertexData.applyToMesh(torusKnot, options.updatable);
  49583. return torusKnot;
  49584. };
  49585. /**
  49586. * Creates a line system mesh.
  49587. * A line system is a pool of many lines gathered in a single mesh.
  49588. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  49589. * 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.
  49590. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  49591. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  49592. * 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
  49593. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  49594. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  49595. * 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
  49596. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  49597. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49598. */
  49599. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  49600. var instance = options.instance;
  49601. var lines = options.lines;
  49602. var colors = options.colors;
  49603. if (instance) {
  49604. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49605. var vertexColor;
  49606. var lineColors;
  49607. if (colors) {
  49608. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49609. }
  49610. var i = 0;
  49611. var c = 0;
  49612. for (var l = 0; l < lines.length; l++) {
  49613. var points = lines[l];
  49614. for (var p = 0; p < points.length; p++) {
  49615. positions[i] = points[p].x;
  49616. positions[i + 1] = points[p].y;
  49617. positions[i + 2] = points[p].z;
  49618. if (colors && vertexColor) {
  49619. lineColors = colors[l];
  49620. vertexColor[c] = lineColors[p].r;
  49621. vertexColor[c + 1] = lineColors[p].g;
  49622. vertexColor[c + 2] = lineColors[p].b;
  49623. vertexColor[c + 3] = lineColors[p].a;
  49624. c += 4;
  49625. }
  49626. i += 3;
  49627. }
  49628. }
  49629. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49630. if (colors && vertexColor) {
  49631. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  49632. }
  49633. return instance;
  49634. }
  49635. // line system creation
  49636. var useVertexColor = (colors) ? true : false;
  49637. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  49638. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  49639. vertexData.applyToMesh(lineSystem, options.updatable);
  49640. return lineSystem;
  49641. };
  49642. /**
  49643. * Creates a line mesh.
  49644. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  49645. * 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.
  49646. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49647. * The parameter `points` is an array successive Vector3.
  49648. * 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
  49649. * The optional parameter `colors` is an array of successive Color4, one per line point.
  49650. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  49651. * When updating an instance, remember that only point positions can change, not the number of points.
  49652. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49653. */
  49654. MeshBuilder.CreateLines = function (name, options, scene) {
  49655. if (scene === void 0) { scene = null; }
  49656. var colors = (options.colors) ? [options.colors] : null;
  49657. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  49658. return lines;
  49659. };
  49660. /**
  49661. * Creates a dashed line mesh.
  49662. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  49663. * 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.
  49664. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49665. * The parameter `points` is an array successive Vector3.
  49666. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  49667. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  49668. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  49669. * 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
  49670. * When updating an instance, remember that only point positions can change, not the number of points.
  49671. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49672. */
  49673. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  49674. if (scene === void 0) { scene = null; }
  49675. var points = options.points;
  49676. var instance = options.instance;
  49677. var gapSize = options.gapSize || 1;
  49678. var dashSize = options.dashSize || 3;
  49679. if (instance) {
  49680. var positionFunction = function (positions) {
  49681. var curvect = BABYLON.Vector3.Zero();
  49682. var nbSeg = positions.length / 6;
  49683. var lg = 0;
  49684. var nb = 0;
  49685. var shft = 0;
  49686. var dashshft = 0;
  49687. var curshft = 0;
  49688. var p = 0;
  49689. var i = 0;
  49690. var j = 0;
  49691. for (i = 0; i < points.length - 1; i++) {
  49692. points[i + 1].subtractToRef(points[i], curvect);
  49693. lg += curvect.length();
  49694. }
  49695. shft = lg / nbSeg;
  49696. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  49697. for (i = 0; i < points.length - 1; i++) {
  49698. points[i + 1].subtractToRef(points[i], curvect);
  49699. nb = Math.floor(curvect.length() / shft);
  49700. curvect.normalize();
  49701. j = 0;
  49702. while (j < nb && p < positions.length) {
  49703. curshft = shft * j;
  49704. positions[p] = points[i].x + curshft * curvect.x;
  49705. positions[p + 1] = points[i].y + curshft * curvect.y;
  49706. positions[p + 2] = points[i].z + curshft * curvect.z;
  49707. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  49708. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  49709. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  49710. p += 6;
  49711. j++;
  49712. }
  49713. }
  49714. while (p < positions.length) {
  49715. positions[p] = points[i].x;
  49716. positions[p + 1] = points[i].y;
  49717. positions[p + 2] = points[i].z;
  49718. p += 3;
  49719. }
  49720. };
  49721. instance.updateMeshPositions(positionFunction, false);
  49722. return instance;
  49723. }
  49724. // dashed lines creation
  49725. var dashedLines = new BABYLON.LinesMesh(name, scene);
  49726. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  49727. vertexData.applyToMesh(dashedLines, options.updatable);
  49728. dashedLines.dashSize = dashSize;
  49729. dashedLines.gapSize = gapSize;
  49730. return dashedLines;
  49731. };
  49732. /**
  49733. * Creates an extruded shape mesh.
  49734. * 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.
  49735. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  49736. *
  49737. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49738. * 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
  49739. * extruded along the Z axis.
  49740. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49741. * 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.
  49742. * The parameter `scale` (float, default 1) is the value to scale the shape.
  49743. * 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
  49744. * 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
  49745. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49746. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49747. * 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).
  49748. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49749. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49750. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49751. */
  49752. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  49753. if (scene === void 0) { scene = null; }
  49754. var path = options.path;
  49755. var shape = options.shape;
  49756. var scale = options.scale || 1;
  49757. var rotation = options.rotation || 0;
  49758. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49759. var updatable = options.updatable;
  49760. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49761. var instance = options.instance || null;
  49762. var invertUV = options.invertUV || false;
  49763. 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);
  49764. };
  49765. /**
  49766. * Creates an custom extruded shape mesh.
  49767. * 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.
  49768. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  49769. *
  49770. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49771. * 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
  49772. * extruded along the Z axis.
  49773. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49774. * 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
  49775. * and the distance of this point from the begining of the path :
  49776. * ```javascript
  49777. * var rotationFunction = function(i, distance) {
  49778. * // do things
  49779. * return rotationValue; }
  49780. * ```
  49781. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  49782. * 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
  49783. * and the distance of this point from the begining of the path :
  49784. * ```javascript
  49785. * var scaleFunction = function(i, distance) {
  49786. * // do things
  49787. * return scaleValue;}
  49788. * ```
  49789. * It must returns a float value that will be the scale value applied to the shape on each path point.
  49790. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  49791. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  49792. * 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
  49793. * 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
  49794. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49795. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49796. * 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).
  49797. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49798. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49799. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49800. */
  49801. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  49802. var path = options.path;
  49803. var shape = options.shape;
  49804. var scaleFunction = options.scaleFunction || (function () { return 1; });
  49805. var rotationFunction = options.rotationFunction || (function () { return 0; });
  49806. var ribbonCloseArray = options.ribbonCloseArray || false;
  49807. var ribbonClosePath = options.ribbonClosePath || false;
  49808. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49809. var updatable = options.updatable;
  49810. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49811. var instance = options.instance;
  49812. var invertUV = options.invertUV || false;
  49813. 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);
  49814. };
  49815. /**
  49816. * Creates lathe mesh.
  49817. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  49818. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  49819. *
  49820. * 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
  49821. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  49822. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  49823. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  49824. * 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.
  49825. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  49826. * 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
  49827. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49828. * 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).
  49829. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49830. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49831. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49832. */
  49833. MeshBuilder.CreateLathe = function (name, options, scene) {
  49834. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  49835. var closed = (options.closed === undefined) ? true : options.closed;
  49836. var shape = options.shape;
  49837. var radius = options.radius || 1;
  49838. var tessellation = options.tessellation || 64;
  49839. var updatable = options.updatable;
  49840. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49841. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  49842. var pi2 = Math.PI * 2;
  49843. var paths = new Array();
  49844. var invertUV = options.invertUV || false;
  49845. var i = 0;
  49846. var p = 0;
  49847. var step = pi2 / tessellation * arc;
  49848. var rotated;
  49849. var path = new Array();
  49850. ;
  49851. for (i = 0; i <= tessellation; i++) {
  49852. var path = [];
  49853. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  49854. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  49855. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  49856. }
  49857. for (p = 0; p < shape.length; p++) {
  49858. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  49859. path.push(rotated);
  49860. }
  49861. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  49862. 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));
  49863. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  49864. }
  49865. paths.push(path);
  49866. }
  49867. // lathe ribbon
  49868. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  49869. return lathe;
  49870. };
  49871. /**
  49872. * Creates a plane mesh.
  49873. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  49874. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  49875. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  49876. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  49877. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49878. * 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).
  49879. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49880. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49881. */
  49882. MeshBuilder.CreatePlane = function (name, options, scene) {
  49883. var plane = new BABYLON.Mesh(name, scene);
  49884. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49885. plane._originalBuilderSideOrientation = options.sideOrientation;
  49886. var vertexData = BABYLON.VertexData.CreatePlane(options);
  49887. vertexData.applyToMesh(plane, options.updatable);
  49888. if (options.sourcePlane) {
  49889. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  49890. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  49891. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  49892. plane.rotate(vectorProduct, product);
  49893. }
  49894. return plane;
  49895. };
  49896. /**
  49897. * Creates a ground mesh.
  49898. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  49899. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  49900. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  49901. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49902. */
  49903. MeshBuilder.CreateGround = function (name, options, scene) {
  49904. var ground = new BABYLON.GroundMesh(name, scene);
  49905. ground._setReady(false);
  49906. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  49907. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  49908. ground._width = options.width || 1;
  49909. ground._height = options.height || 1;
  49910. ground._maxX = ground._width / 2;
  49911. ground._maxZ = ground._height / 2;
  49912. ground._minX = -ground._maxX;
  49913. ground._minZ = -ground._maxZ;
  49914. var vertexData = BABYLON.VertexData.CreateGround(options);
  49915. vertexData.applyToMesh(ground, options.updatable);
  49916. ground._setReady(true);
  49917. return ground;
  49918. };
  49919. /**
  49920. * Creates a tiled ground mesh.
  49921. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  49922. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  49923. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  49924. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  49925. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  49926. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  49927. * numbers of subdivisions on the ground width and height of each tile.
  49928. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49929. */
  49930. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  49931. var tiledGround = new BABYLON.Mesh(name, scene);
  49932. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  49933. vertexData.applyToMesh(tiledGround, options.updatable);
  49934. return tiledGround;
  49935. };
  49936. /**
  49937. * Creates a ground mesh from a height map.
  49938. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  49939. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  49940. * The parameter `url` sets the URL of the height map image resource.
  49941. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  49942. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  49943. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  49944. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  49945. * 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.
  49946. * 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).
  49947. * This function is passed the newly built mesh :
  49948. * ```javascript
  49949. * function(mesh) { // do things
  49950. * return; }
  49951. * ```
  49952. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49953. */
  49954. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  49955. var width = options.width || 10.0;
  49956. var height = options.height || 10.0;
  49957. var subdivisions = options.subdivisions || 1 | 0;
  49958. var minHeight = options.minHeight || 0.0;
  49959. var maxHeight = options.maxHeight || 1.0;
  49960. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  49961. var updatable = options.updatable;
  49962. var onReady = options.onReady;
  49963. var ground = new BABYLON.GroundMesh(name, scene);
  49964. ground._subdivisionsX = subdivisions;
  49965. ground._subdivisionsY = subdivisions;
  49966. ground._width = width;
  49967. ground._height = height;
  49968. ground._maxX = ground._width / 2.0;
  49969. ground._maxZ = ground._height / 2.0;
  49970. ground._minX = -ground._maxX;
  49971. ground._minZ = -ground._maxZ;
  49972. ground._setReady(false);
  49973. var onload = function (img) {
  49974. // Getting height map data
  49975. var canvas = document.createElement("canvas");
  49976. var context = canvas.getContext("2d");
  49977. if (!context) {
  49978. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  49979. }
  49980. if (scene.isDisposed) {
  49981. return;
  49982. }
  49983. var bufferWidth = img.width;
  49984. var bufferHeight = img.height;
  49985. canvas.width = bufferWidth;
  49986. canvas.height = bufferHeight;
  49987. context.drawImage(img, 0, 0);
  49988. // Create VertexData from map data
  49989. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  49990. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  49991. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  49992. width: width, height: height,
  49993. subdivisions: subdivisions,
  49994. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  49995. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  49996. });
  49997. vertexData.applyToMesh(ground, updatable);
  49998. ground._setReady(true);
  49999. //execute ready callback, if set
  50000. if (onReady) {
  50001. onReady(ground);
  50002. }
  50003. };
  50004. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  50005. return ground;
  50006. };
  50007. /**
  50008. * Creates a polygon mesh.
  50009. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  50010. * 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.
  50011. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50012. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50013. * 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).
  50014. * Remember you can only change the shape positions, not their number when updating a polygon.
  50015. */
  50016. MeshBuilder.CreatePolygon = function (name, options, scene) {
  50017. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50018. var shape = options.shape;
  50019. var holes = options.holes || [];
  50020. var depth = options.depth || 0;
  50021. var contours = [];
  50022. var hole = [];
  50023. for (var i = 0; i < shape.length; i++) {
  50024. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  50025. }
  50026. var epsilon = 0.00000001;
  50027. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  50028. contours.pop();
  50029. }
  50030. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  50031. for (var hNb = 0; hNb < holes.length; hNb++) {
  50032. hole = [];
  50033. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  50034. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  50035. }
  50036. polygonTriangulation.addHole(hole);
  50037. }
  50038. var polygon = polygonTriangulation.build(options.updatable, depth);
  50039. polygon._originalBuilderSideOrientation = options.sideOrientation;
  50040. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  50041. vertexData.applyToMesh(polygon, options.updatable);
  50042. return polygon;
  50043. };
  50044. ;
  50045. /**
  50046. * Creates an extruded polygon mesh, with depth in the Y direction.
  50047. * 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).
  50048. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  50049. */
  50050. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  50051. return MeshBuilder.CreatePolygon(name, options, scene);
  50052. };
  50053. ;
  50054. /**
  50055. * Creates a tube mesh.
  50056. * 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.
  50057. *
  50058. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  50059. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  50060. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  50061. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  50062. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  50063. * 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.
  50064. * It must return a radius value (positive float) :
  50065. * ```javascript
  50066. * var radiusFunction = function(i, distance) {
  50067. * // do things
  50068. * return radius; }
  50069. * ```
  50070. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  50071. * 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
  50072. * 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
  50073. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50074. * 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).
  50075. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50076. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  50077. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50078. */
  50079. MeshBuilder.CreateTube = function (name, options, scene) {
  50080. var path = options.path;
  50081. var instance = options.instance;
  50082. var radius = 1.0;
  50083. if (instance) {
  50084. radius = instance.radius;
  50085. }
  50086. if (options.radius !== undefined) {
  50087. radius = options.radius;
  50088. }
  50089. ;
  50090. var tessellation = options.tessellation || 64 | 0;
  50091. var radiusFunction = options.radiusFunction || null;
  50092. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  50093. var invertUV = options.invertUV || false;
  50094. var updatable = options.updatable;
  50095. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50096. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  50097. // tube geometry
  50098. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  50099. var tangents = path3D.getTangents();
  50100. var normals = path3D.getNormals();
  50101. var distances = path3D.getDistances();
  50102. var pi2 = Math.PI * 2;
  50103. var step = pi2 / tessellation * arc;
  50104. var returnRadius = function () { return radius; };
  50105. var radiusFunctionFinal = radiusFunction || returnRadius;
  50106. var circlePath;
  50107. var rad;
  50108. var normal;
  50109. var rotated;
  50110. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  50111. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  50112. for (var i = 0; i < path.length; i++) {
  50113. rad = radiusFunctionFinal(i, distances[i]); // current radius
  50114. circlePath = Array(); // current circle array
  50115. normal = normals[i]; // current normal
  50116. for (var t = 0; t < tessellation; t++) {
  50117. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  50118. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  50119. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  50120. rotated.scaleInPlace(rad).addInPlace(path[i]);
  50121. circlePath[t] = rotated;
  50122. }
  50123. circlePaths[index] = circlePath;
  50124. index++;
  50125. }
  50126. // cap
  50127. var capPath = function (nbPoints, pathIndex) {
  50128. var pointCap = Array();
  50129. for (var i = 0; i < nbPoints; i++) {
  50130. pointCap.push(path[pathIndex]);
  50131. }
  50132. return pointCap;
  50133. };
  50134. switch (cap) {
  50135. case BABYLON.Mesh.NO_CAP:
  50136. break;
  50137. case BABYLON.Mesh.CAP_START:
  50138. circlePaths[0] = capPath(tessellation, 0);
  50139. circlePaths[1] = circlePaths[2].slice(0);
  50140. break;
  50141. case BABYLON.Mesh.CAP_END:
  50142. circlePaths[index] = circlePaths[index - 1].slice(0);
  50143. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  50144. break;
  50145. case BABYLON.Mesh.CAP_ALL:
  50146. circlePaths[0] = capPath(tessellation, 0);
  50147. circlePaths[1] = circlePaths[2].slice(0);
  50148. circlePaths[index] = circlePaths[index - 1].slice(0);
  50149. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  50150. break;
  50151. default:
  50152. break;
  50153. }
  50154. return circlePaths;
  50155. };
  50156. var path3D;
  50157. var pathArray;
  50158. if (instance) {
  50159. var arc = options.arc || instance.arc;
  50160. path3D = (instance.path3D).update(path);
  50161. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  50162. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  50163. instance.path3D = path3D;
  50164. instance.pathArray = pathArray;
  50165. instance.arc = arc;
  50166. instance.radius = radius;
  50167. return instance;
  50168. }
  50169. // tube creation
  50170. path3D = new BABYLON.Path3D(path);
  50171. var newPathArray = new Array();
  50172. cap = (cap < 0 || cap > 3) ? 0 : cap;
  50173. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  50174. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  50175. tube.pathArray = pathArray;
  50176. tube.path3D = path3D;
  50177. tube.tessellation = tessellation;
  50178. tube.cap = cap;
  50179. tube.arc = options.arc;
  50180. tube.radius = radius;
  50181. return tube;
  50182. };
  50183. /**
  50184. * Creates a polyhedron mesh.
  50185. *
  50186. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  50187. * 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
  50188. * to choose the wanted type.
  50189. * The parameter `size` (positive float, default 1) sets the polygon size.
  50190. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  50191. * 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`.
  50192. * 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
  50193. * 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)`).
  50194. * 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
  50195. * 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.
  50196. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50197. * 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).
  50198. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50199. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50200. */
  50201. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  50202. var polyhedron = new BABYLON.Mesh(name, scene);
  50203. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50204. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  50205. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  50206. vertexData.applyToMesh(polyhedron, options.updatable);
  50207. return polyhedron;
  50208. };
  50209. /**
  50210. * Creates a decal mesh.
  50211. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  50212. * 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.
  50213. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  50214. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  50215. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  50216. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  50217. */
  50218. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  50219. var indices = sourceMesh.getIndices();
  50220. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50221. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50222. var position = options.position || BABYLON.Vector3.Zero();
  50223. var normal = options.normal || BABYLON.Vector3.Up();
  50224. var size = options.size || BABYLON.Vector3.One();
  50225. var angle = options.angle || 0;
  50226. // Getting correct rotation
  50227. if (!normal) {
  50228. var target = new BABYLON.Vector3(0, 0, 1);
  50229. var camera = sourceMesh.getScene().activeCamera;
  50230. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  50231. normal = camera.globalPosition.subtract(cameraWorldTarget);
  50232. }
  50233. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  50234. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  50235. var pitch = Math.atan2(normal.y, len);
  50236. // Matrix
  50237. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  50238. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  50239. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  50240. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  50241. var vertexData = new BABYLON.VertexData();
  50242. vertexData.indices = [];
  50243. vertexData.positions = [];
  50244. vertexData.normals = [];
  50245. vertexData.uvs = [];
  50246. var currentVertexDataIndex = 0;
  50247. var extractDecalVector3 = function (indexId) {
  50248. var result = new BABYLON.PositionNormalVertex();
  50249. if (!indices || !positions || !normals) {
  50250. return result;
  50251. }
  50252. var vertexId = indices[indexId];
  50253. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  50254. // Send vector to decal local world
  50255. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  50256. // Get normal
  50257. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  50258. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  50259. return result;
  50260. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  50261. var clip = function (vertices, axis) {
  50262. if (vertices.length === 0) {
  50263. return vertices;
  50264. }
  50265. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  50266. var clipVertices = function (v0, v1) {
  50267. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  50268. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  50269. };
  50270. var result = new Array();
  50271. for (var index = 0; index < vertices.length; index += 3) {
  50272. var v1Out;
  50273. var v2Out;
  50274. var v3Out;
  50275. var total = 0;
  50276. var nV1 = null;
  50277. var nV2 = null;
  50278. var nV3 = null;
  50279. var nV4 = null;
  50280. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  50281. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  50282. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  50283. v1Out = d1 > 0;
  50284. v2Out = d2 > 0;
  50285. v3Out = d3 > 0;
  50286. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  50287. switch (total) {
  50288. case 0:
  50289. result.push(vertices[index]);
  50290. result.push(vertices[index + 1]);
  50291. result.push(vertices[index + 2]);
  50292. break;
  50293. case 1:
  50294. if (v1Out) {
  50295. nV1 = vertices[index + 1];
  50296. nV2 = vertices[index + 2];
  50297. nV3 = clipVertices(vertices[index], nV1);
  50298. nV4 = clipVertices(vertices[index], nV2);
  50299. }
  50300. if (v2Out) {
  50301. nV1 = vertices[index];
  50302. nV2 = vertices[index + 2];
  50303. nV3 = clipVertices(vertices[index + 1], nV1);
  50304. nV4 = clipVertices(vertices[index + 1], nV2);
  50305. result.push(nV3);
  50306. result.push(nV2.clone());
  50307. result.push(nV1.clone());
  50308. result.push(nV2.clone());
  50309. result.push(nV3.clone());
  50310. result.push(nV4);
  50311. break;
  50312. }
  50313. if (v3Out) {
  50314. nV1 = vertices[index];
  50315. nV2 = vertices[index + 1];
  50316. nV3 = clipVertices(vertices[index + 2], nV1);
  50317. nV4 = clipVertices(vertices[index + 2], nV2);
  50318. }
  50319. if (nV1 && nV2 && nV3 && nV4) {
  50320. result.push(nV1.clone());
  50321. result.push(nV2.clone());
  50322. result.push(nV3);
  50323. result.push(nV4);
  50324. result.push(nV3.clone());
  50325. result.push(nV2.clone());
  50326. }
  50327. break;
  50328. case 2:
  50329. if (!v1Out) {
  50330. nV1 = vertices[index].clone();
  50331. nV2 = clipVertices(nV1, vertices[index + 1]);
  50332. nV3 = clipVertices(nV1, vertices[index + 2]);
  50333. result.push(nV1);
  50334. result.push(nV2);
  50335. result.push(nV3);
  50336. }
  50337. if (!v2Out) {
  50338. nV1 = vertices[index + 1].clone();
  50339. nV2 = clipVertices(nV1, vertices[index + 2]);
  50340. nV3 = clipVertices(nV1, vertices[index]);
  50341. result.push(nV1);
  50342. result.push(nV2);
  50343. result.push(nV3);
  50344. }
  50345. if (!v3Out) {
  50346. nV1 = vertices[index + 2].clone();
  50347. nV2 = clipVertices(nV1, vertices[index]);
  50348. nV3 = clipVertices(nV1, vertices[index + 1]);
  50349. result.push(nV1);
  50350. result.push(nV2);
  50351. result.push(nV3);
  50352. }
  50353. break;
  50354. case 3:
  50355. break;
  50356. }
  50357. }
  50358. return result;
  50359. };
  50360. for (var index = 0; index < indices.length; index += 3) {
  50361. var faceVertices = new Array();
  50362. faceVertices.push(extractDecalVector3(index));
  50363. faceVertices.push(extractDecalVector3(index + 1));
  50364. faceVertices.push(extractDecalVector3(index + 2));
  50365. // Clip
  50366. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  50367. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  50368. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  50369. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  50370. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  50371. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  50372. if (faceVertices.length === 0) {
  50373. continue;
  50374. }
  50375. // Add UVs and get back to world
  50376. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  50377. var vertex = faceVertices[vIndex];
  50378. //TODO check for Int32Array | Uint32Array | Uint16Array
  50379. vertexData.indices.push(currentVertexDataIndex);
  50380. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  50381. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  50382. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  50383. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  50384. currentVertexDataIndex++;
  50385. }
  50386. }
  50387. // Return mesh
  50388. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  50389. vertexData.applyToMesh(decal);
  50390. decal.position = position.clone();
  50391. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  50392. return decal;
  50393. };
  50394. // Privates
  50395. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  50396. // extrusion geometry
  50397. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  50398. var tangents = path3D.getTangents();
  50399. var normals = path3D.getNormals();
  50400. var binormals = path3D.getBinormals();
  50401. var distances = path3D.getDistances();
  50402. var angle = 0;
  50403. var returnScale = function () { return scale !== null ? scale : 1; };
  50404. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  50405. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  50406. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  50407. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  50408. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  50409. for (var i = 0; i < curve.length; i++) {
  50410. var shapePath = new Array();
  50411. var angleStep = rotate(i, distances[i]);
  50412. var scaleRatio = scl(i, distances[i]);
  50413. for (var p = 0; p < shape.length; p++) {
  50414. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  50415. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  50416. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  50417. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  50418. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  50419. shapePath[p] = rotated;
  50420. }
  50421. shapePaths[index] = shapePath;
  50422. angle += angleStep;
  50423. index++;
  50424. }
  50425. // cap
  50426. var capPath = function (shapePath) {
  50427. var pointCap = Array();
  50428. var barycenter = BABYLON.Vector3.Zero();
  50429. var i;
  50430. for (i = 0; i < shapePath.length; i++) {
  50431. barycenter.addInPlace(shapePath[i]);
  50432. }
  50433. barycenter.scaleInPlace(1.0 / shapePath.length);
  50434. for (i = 0; i < shapePath.length; i++) {
  50435. pointCap.push(barycenter);
  50436. }
  50437. return pointCap;
  50438. };
  50439. switch (cap) {
  50440. case BABYLON.Mesh.NO_CAP:
  50441. break;
  50442. case BABYLON.Mesh.CAP_START:
  50443. shapePaths[0] = capPath(shapePaths[2]);
  50444. shapePaths[1] = shapePaths[2];
  50445. break;
  50446. case BABYLON.Mesh.CAP_END:
  50447. shapePaths[index] = shapePaths[index - 1];
  50448. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  50449. break;
  50450. case BABYLON.Mesh.CAP_ALL:
  50451. shapePaths[0] = capPath(shapePaths[2]);
  50452. shapePaths[1] = shapePaths[2];
  50453. shapePaths[index] = shapePaths[index - 1];
  50454. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  50455. break;
  50456. default:
  50457. break;
  50458. }
  50459. return shapePaths;
  50460. };
  50461. var path3D;
  50462. var pathArray;
  50463. if (instance) {
  50464. path3D = (instance.path3D).update(curve);
  50465. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  50466. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  50467. return instance;
  50468. }
  50469. // extruded shape creation
  50470. path3D = new BABYLON.Path3D(curve);
  50471. var newShapePaths = new Array();
  50472. cap = (cap < 0 || cap > 3) ? 0 : cap;
  50473. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  50474. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  50475. extrudedGeneric.pathArray = pathArray;
  50476. extrudedGeneric.path3D = path3D;
  50477. extrudedGeneric.cap = cap;
  50478. return extrudedGeneric;
  50479. };
  50480. return MeshBuilder;
  50481. }());
  50482. BABYLON.MeshBuilder = MeshBuilder;
  50483. })(BABYLON || (BABYLON = {}));
  50484. //# sourceMappingURL=babylon.meshBuilder.js.map
  50485. var BABYLON;
  50486. (function (BABYLON) {
  50487. var AudioEngine = /** @class */ (function () {
  50488. function AudioEngine() {
  50489. this._audioContext = null;
  50490. this._audioContextInitialized = false;
  50491. this.canUseWebAudio = false;
  50492. this.WarnedWebAudioUnsupported = false;
  50493. this.unlocked = false;
  50494. this.isMP3supported = false;
  50495. this.isOGGsupported = false;
  50496. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  50497. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  50498. this.canUseWebAudio = true;
  50499. }
  50500. var audioElem = document.createElement('audio');
  50501. try {
  50502. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  50503. this.isMP3supported = true;
  50504. }
  50505. }
  50506. catch (e) {
  50507. // protect error during capability check.
  50508. }
  50509. try {
  50510. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  50511. this.isOGGsupported = true;
  50512. }
  50513. }
  50514. catch (e) {
  50515. // protect error during capability check.
  50516. }
  50517. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  50518. this._unlockiOSaudio();
  50519. }
  50520. else {
  50521. this.unlocked = true;
  50522. }
  50523. }
  50524. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  50525. get: function () {
  50526. if (!this._audioContextInitialized) {
  50527. this._initializeAudioContext();
  50528. }
  50529. return this._audioContext;
  50530. },
  50531. enumerable: true,
  50532. configurable: true
  50533. });
  50534. AudioEngine.prototype._unlockiOSaudio = function () {
  50535. var _this = this;
  50536. var unlockaudio = function () {
  50537. if (!_this.audioContext) {
  50538. return;
  50539. }
  50540. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  50541. var source = _this.audioContext.createBufferSource();
  50542. source.buffer = buffer;
  50543. source.connect(_this.audioContext.destination);
  50544. source.start(0);
  50545. setTimeout(function () {
  50546. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  50547. _this.unlocked = true;
  50548. window.removeEventListener('touchend', unlockaudio, false);
  50549. if (_this.onAudioUnlocked) {
  50550. _this.onAudioUnlocked();
  50551. }
  50552. }
  50553. }, 0);
  50554. };
  50555. window.addEventListener('touchend', unlockaudio, false);
  50556. };
  50557. AudioEngine.prototype._initializeAudioContext = function () {
  50558. try {
  50559. if (this.canUseWebAudio) {
  50560. this._audioContext = new AudioContext();
  50561. // create a global volume gain node
  50562. this.masterGain = this._audioContext.createGain();
  50563. this.masterGain.gain.value = 1;
  50564. this.masterGain.connect(this._audioContext.destination);
  50565. this._audioContextInitialized = true;
  50566. }
  50567. }
  50568. catch (e) {
  50569. this.canUseWebAudio = false;
  50570. BABYLON.Tools.Error("Web Audio: " + e.message);
  50571. }
  50572. };
  50573. AudioEngine.prototype.dispose = function () {
  50574. if (this.canUseWebAudio && this._audioContextInitialized) {
  50575. if (this._connectedAnalyser && this._audioContext) {
  50576. this._connectedAnalyser.stopDebugCanvas();
  50577. this._connectedAnalyser.dispose();
  50578. this.masterGain.disconnect();
  50579. this.masterGain.connect(this._audioContext.destination);
  50580. this._connectedAnalyser = null;
  50581. }
  50582. this.masterGain.gain.value = 1;
  50583. }
  50584. this.WarnedWebAudioUnsupported = false;
  50585. };
  50586. AudioEngine.prototype.getGlobalVolume = function () {
  50587. if (this.canUseWebAudio && this._audioContextInitialized) {
  50588. return this.masterGain.gain.value;
  50589. }
  50590. else {
  50591. return -1;
  50592. }
  50593. };
  50594. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  50595. if (this.canUseWebAudio && this._audioContextInitialized) {
  50596. this.masterGain.gain.value = newVolume;
  50597. }
  50598. };
  50599. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  50600. if (this._connectedAnalyser) {
  50601. this._connectedAnalyser.stopDebugCanvas();
  50602. }
  50603. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  50604. this._connectedAnalyser = analyser;
  50605. this.masterGain.disconnect();
  50606. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  50607. }
  50608. };
  50609. return AudioEngine;
  50610. }());
  50611. BABYLON.AudioEngine = AudioEngine;
  50612. })(BABYLON || (BABYLON = {}));
  50613. //# sourceMappingURL=babylon.audioEngine.js.map
  50614. var BABYLON;
  50615. (function (BABYLON) {
  50616. var Sound = /** @class */ (function () {
  50617. /**
  50618. * Create a sound and attach it to a scene
  50619. * @param name Name of your sound
  50620. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  50621. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  50622. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  50623. */
  50624. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  50625. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  50626. var _this = this;
  50627. this.autoplay = false;
  50628. this.loop = false;
  50629. this.useCustomAttenuation = false;
  50630. this.spatialSound = false;
  50631. this.refDistance = 1;
  50632. this.rolloffFactor = 1;
  50633. this.maxDistance = 100;
  50634. this.distanceModel = "linear";
  50635. this._panningModel = "equalpower";
  50636. this._playbackRate = 1;
  50637. this._streaming = false;
  50638. this._startTime = 0;
  50639. this._startOffset = 0;
  50640. this._position = BABYLON.Vector3.Zero();
  50641. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  50642. this._volume = 1;
  50643. this._isReadyToPlay = false;
  50644. this.isPlaying = false;
  50645. this.isPaused = false;
  50646. this._isDirectional = false;
  50647. // Used if you'd like to create a directional sound.
  50648. // If not set, the sound will be omnidirectional
  50649. this._coneInnerAngle = 360;
  50650. this._coneOuterAngle = 360;
  50651. this._coneOuterGain = 0;
  50652. this._isOutputConnected = false;
  50653. this._urlType = "Unknown";
  50654. this.name = name;
  50655. this._scene = scene;
  50656. this._readyToPlayCallback = readyToPlayCallback;
  50657. // Default custom attenuation function is a linear attenuation
  50658. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  50659. if (currentDistance < maxDistance) {
  50660. return currentVolume * (1 - currentDistance / maxDistance);
  50661. }
  50662. else {
  50663. return 0;
  50664. }
  50665. };
  50666. if (options) {
  50667. this.autoplay = options.autoplay || false;
  50668. this.loop = options.loop || false;
  50669. // if volume === 0, we need another way to check this option
  50670. if (options.volume !== undefined) {
  50671. this._volume = options.volume;
  50672. }
  50673. this.spatialSound = options.spatialSound || false;
  50674. this.maxDistance = options.maxDistance || 100;
  50675. this.useCustomAttenuation = options.useCustomAttenuation || false;
  50676. this.rolloffFactor = options.rolloffFactor || 1;
  50677. this.refDistance = options.refDistance || 1;
  50678. this.distanceModel = options.distanceModel || "linear";
  50679. this._playbackRate = options.playbackRate || 1;
  50680. this._streaming = options.streaming || false;
  50681. }
  50682. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50683. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  50684. this._soundGain.gain.value = this._volume;
  50685. this._inputAudioNode = this._soundGain;
  50686. this._ouputAudioNode = this._soundGain;
  50687. if (this.spatialSound) {
  50688. this._createSpatialParameters();
  50689. }
  50690. this._scene.mainSoundTrack.AddSound(this);
  50691. var validParameter = true;
  50692. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  50693. if (urlOrArrayBuffer) {
  50694. if (typeof (urlOrArrayBuffer) === "string")
  50695. this._urlType = "String";
  50696. if (Array.isArray(urlOrArrayBuffer))
  50697. this._urlType = "Array";
  50698. if (urlOrArrayBuffer instanceof ArrayBuffer)
  50699. this._urlType = "ArrayBuffer";
  50700. var urls = [];
  50701. var codecSupportedFound = false;
  50702. switch (this._urlType) {
  50703. case "ArrayBuffer":
  50704. if (urlOrArrayBuffer.byteLength > 0) {
  50705. codecSupportedFound = true;
  50706. this._soundLoaded(urlOrArrayBuffer);
  50707. }
  50708. break;
  50709. case "String":
  50710. urls.push(urlOrArrayBuffer);
  50711. case "Array":
  50712. if (urls.length === 0)
  50713. urls = urlOrArrayBuffer;
  50714. // If we found a supported format, we load it immediately and stop the loop
  50715. for (var i = 0; i < urls.length; i++) {
  50716. var url = urls[i];
  50717. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  50718. codecSupportedFound = true;
  50719. }
  50720. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  50721. codecSupportedFound = true;
  50722. }
  50723. if (url.indexOf(".wav", url.length - 4) !== -1) {
  50724. codecSupportedFound = true;
  50725. }
  50726. if (url.indexOf("blob:") !== -1) {
  50727. codecSupportedFound = true;
  50728. }
  50729. if (codecSupportedFound) {
  50730. // Loading sound using XHR2
  50731. if (!this._streaming) {
  50732. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  50733. }
  50734. else {
  50735. this._htmlAudioElement = new Audio(url);
  50736. this._htmlAudioElement.controls = false;
  50737. this._htmlAudioElement.loop = this.loop;
  50738. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  50739. this._htmlAudioElement.preload = "auto";
  50740. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  50741. _this._isReadyToPlay = true;
  50742. if (_this.autoplay) {
  50743. _this.play();
  50744. }
  50745. if (_this._readyToPlayCallback) {
  50746. _this._readyToPlayCallback();
  50747. }
  50748. });
  50749. document.body.appendChild(this._htmlAudioElement);
  50750. }
  50751. break;
  50752. }
  50753. }
  50754. break;
  50755. default:
  50756. validParameter = false;
  50757. break;
  50758. }
  50759. if (!validParameter) {
  50760. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  50761. }
  50762. else {
  50763. if (!codecSupportedFound) {
  50764. this._isReadyToPlay = true;
  50765. // Simulating a ready to play event to avoid breaking code path
  50766. if (this._readyToPlayCallback) {
  50767. window.setTimeout(function () {
  50768. if (_this._readyToPlayCallback) {
  50769. _this._readyToPlayCallback();
  50770. }
  50771. }, 1000);
  50772. }
  50773. }
  50774. }
  50775. }
  50776. }
  50777. else {
  50778. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  50779. this._scene.mainSoundTrack.AddSound(this);
  50780. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  50781. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  50782. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  50783. }
  50784. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  50785. if (this._readyToPlayCallback) {
  50786. window.setTimeout(function () {
  50787. if (_this._readyToPlayCallback) {
  50788. _this._readyToPlayCallback();
  50789. }
  50790. }, 1000);
  50791. }
  50792. }
  50793. }
  50794. Sound.prototype.dispose = function () {
  50795. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  50796. if (this.isPlaying) {
  50797. this.stop();
  50798. }
  50799. this._isReadyToPlay = false;
  50800. if (this.soundTrackId === -1) {
  50801. this._scene.mainSoundTrack.RemoveSound(this);
  50802. }
  50803. else {
  50804. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  50805. }
  50806. if (this._soundGain) {
  50807. this._soundGain.disconnect();
  50808. this._soundGain = null;
  50809. }
  50810. if (this._soundPanner) {
  50811. this._soundPanner.disconnect();
  50812. this._soundPanner = null;
  50813. }
  50814. if (this._soundSource) {
  50815. this._soundSource.disconnect();
  50816. this._soundSource = null;
  50817. }
  50818. this._audioBuffer = null;
  50819. if (this._htmlAudioElement) {
  50820. this._htmlAudioElement.pause();
  50821. this._htmlAudioElement.src = "";
  50822. document.body.removeChild(this._htmlAudioElement);
  50823. }
  50824. if (this._connectedMesh && this._registerFunc) {
  50825. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50826. this._connectedMesh = null;
  50827. }
  50828. }
  50829. };
  50830. Sound.prototype.isReady = function () {
  50831. return this._isReadyToPlay;
  50832. };
  50833. Sound.prototype._soundLoaded = function (audioData) {
  50834. var _this = this;
  50835. if (!BABYLON.Engine.audioEngine.audioContext) {
  50836. return;
  50837. }
  50838. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  50839. _this._audioBuffer = buffer;
  50840. _this._isReadyToPlay = true;
  50841. if (_this.autoplay) {
  50842. _this.play();
  50843. }
  50844. if (_this._readyToPlayCallback) {
  50845. _this._readyToPlayCallback();
  50846. }
  50847. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  50848. };
  50849. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  50850. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50851. this._audioBuffer = audioBuffer;
  50852. this._isReadyToPlay = true;
  50853. }
  50854. };
  50855. Sound.prototype.updateOptions = function (options) {
  50856. if (options) {
  50857. this.loop = options.loop || this.loop;
  50858. this.maxDistance = options.maxDistance || this.maxDistance;
  50859. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  50860. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  50861. this.refDistance = options.refDistance || this.refDistance;
  50862. this.distanceModel = options.distanceModel || this.distanceModel;
  50863. this._playbackRate = options.playbackRate || this._playbackRate;
  50864. this._updateSpatialParameters();
  50865. if (this.isPlaying) {
  50866. if (this._streaming) {
  50867. this._htmlAudioElement.playbackRate = this._playbackRate;
  50868. }
  50869. else {
  50870. if (this._soundSource) {
  50871. this._soundSource.playbackRate.value = this._playbackRate;
  50872. }
  50873. }
  50874. }
  50875. }
  50876. };
  50877. Sound.prototype._createSpatialParameters = function () {
  50878. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50879. if (this._scene.headphone) {
  50880. this._panningModel = "HRTF";
  50881. }
  50882. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  50883. this._updateSpatialParameters();
  50884. this._soundPanner.connect(this._ouputAudioNode);
  50885. this._inputAudioNode = this._soundPanner;
  50886. }
  50887. };
  50888. Sound.prototype._updateSpatialParameters = function () {
  50889. if (this.spatialSound && this._soundPanner) {
  50890. if (this.useCustomAttenuation) {
  50891. // Tricks to disable in a way embedded Web Audio attenuation
  50892. this._soundPanner.distanceModel = "linear";
  50893. this._soundPanner.maxDistance = Number.MAX_VALUE;
  50894. this._soundPanner.refDistance = 1;
  50895. this._soundPanner.rolloffFactor = 1;
  50896. this._soundPanner.panningModel = this._panningModel;
  50897. }
  50898. else {
  50899. this._soundPanner.distanceModel = this.distanceModel;
  50900. this._soundPanner.maxDistance = this.maxDistance;
  50901. this._soundPanner.refDistance = this.refDistance;
  50902. this._soundPanner.rolloffFactor = this.rolloffFactor;
  50903. this._soundPanner.panningModel = this._panningModel;
  50904. }
  50905. }
  50906. };
  50907. Sound.prototype.switchPanningModelToHRTF = function () {
  50908. this._panningModel = "HRTF";
  50909. this._switchPanningModel();
  50910. };
  50911. Sound.prototype.switchPanningModelToEqualPower = function () {
  50912. this._panningModel = "equalpower";
  50913. this._switchPanningModel();
  50914. };
  50915. Sound.prototype._switchPanningModel = function () {
  50916. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  50917. this._soundPanner.panningModel = this._panningModel;
  50918. }
  50919. };
  50920. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  50921. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50922. if (this._isOutputConnected) {
  50923. this._ouputAudioNode.disconnect();
  50924. }
  50925. this._ouputAudioNode.connect(soundTrackAudioNode);
  50926. this._isOutputConnected = true;
  50927. }
  50928. };
  50929. /**
  50930. * Transform this sound into a directional source
  50931. * @param coneInnerAngle Size of the inner cone in degree
  50932. * @param coneOuterAngle Size of the outer cone in degree
  50933. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  50934. */
  50935. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  50936. if (coneOuterAngle < coneInnerAngle) {
  50937. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  50938. return;
  50939. }
  50940. this._coneInnerAngle = coneInnerAngle;
  50941. this._coneOuterAngle = coneOuterAngle;
  50942. this._coneOuterGain = coneOuterGain;
  50943. this._isDirectional = true;
  50944. if (this.isPlaying && this.loop) {
  50945. this.stop();
  50946. this.play();
  50947. }
  50948. };
  50949. Sound.prototype.setPosition = function (newPosition) {
  50950. this._position = newPosition;
  50951. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  50952. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  50953. }
  50954. };
  50955. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  50956. this._localDirection = newLocalDirection;
  50957. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  50958. this._updateDirection();
  50959. }
  50960. };
  50961. Sound.prototype._updateDirection = function () {
  50962. if (!this._connectedMesh || !this._soundPanner) {
  50963. return;
  50964. }
  50965. var mat = this._connectedMesh.getWorldMatrix();
  50966. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  50967. direction.normalize();
  50968. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  50969. };
  50970. Sound.prototype.updateDistanceFromListener = function () {
  50971. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  50972. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  50973. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  50974. }
  50975. };
  50976. Sound.prototype.setAttenuationFunction = function (callback) {
  50977. this._customAttenuationFunction = callback;
  50978. };
  50979. /**
  50980. * Play the sound
  50981. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  50982. * @param offset (optional) Start the sound setting it at a specific time
  50983. */
  50984. Sound.prototype.play = function (time, offset) {
  50985. var _this = this;
  50986. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  50987. try {
  50988. if (this._startOffset < 0) {
  50989. time = -this._startOffset;
  50990. this._startOffset = 0;
  50991. }
  50992. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  50993. if (!this._soundSource || !this._streamingSource) {
  50994. if (this.spatialSound && this._soundPanner) {
  50995. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  50996. if (this._isDirectional) {
  50997. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  50998. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  50999. this._soundPanner.coneOuterGain = this._coneOuterGain;
  51000. if (this._connectedMesh) {
  51001. this._updateDirection();
  51002. }
  51003. else {
  51004. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  51005. }
  51006. }
  51007. }
  51008. }
  51009. if (this._streaming) {
  51010. if (!this._streamingSource) {
  51011. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  51012. this._htmlAudioElement.onended = function () { _this._onended(); };
  51013. this._htmlAudioElement.playbackRate = this._playbackRate;
  51014. }
  51015. this._streamingSource.disconnect();
  51016. this._streamingSource.connect(this._inputAudioNode);
  51017. this._htmlAudioElement.play();
  51018. }
  51019. else {
  51020. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  51021. this._soundSource.buffer = this._audioBuffer;
  51022. this._soundSource.connect(this._inputAudioNode);
  51023. this._soundSource.loop = this.loop;
  51024. this._soundSource.playbackRate.value = this._playbackRate;
  51025. this._soundSource.onended = function () { _this._onended(); };
  51026. if (this._soundSource.buffer) {
  51027. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  51028. }
  51029. }
  51030. this._startTime = startTime;
  51031. this.isPlaying = true;
  51032. this.isPaused = false;
  51033. }
  51034. catch (ex) {
  51035. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  51036. }
  51037. }
  51038. };
  51039. Sound.prototype._onended = function () {
  51040. this.isPlaying = false;
  51041. if (this.onended) {
  51042. this.onended();
  51043. }
  51044. };
  51045. /**
  51046. * Stop the sound
  51047. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  51048. */
  51049. Sound.prototype.stop = function (time) {
  51050. if (this.isPlaying) {
  51051. if (this._streaming) {
  51052. this._htmlAudioElement.pause();
  51053. // Test needed for Firefox or it will generate an Invalid State Error
  51054. if (this._htmlAudioElement.currentTime > 0) {
  51055. this._htmlAudioElement.currentTime = 0;
  51056. }
  51057. }
  51058. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  51059. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  51060. this._soundSource.stop(stopTime);
  51061. this._soundSource.onended = function () { };
  51062. if (!this.isPaused) {
  51063. this._startOffset = 0;
  51064. }
  51065. }
  51066. this.isPlaying = false;
  51067. }
  51068. };
  51069. Sound.prototype.pause = function () {
  51070. if (this.isPlaying) {
  51071. this.isPaused = true;
  51072. if (this._streaming) {
  51073. this._htmlAudioElement.pause();
  51074. }
  51075. else if (BABYLON.Engine.audioEngine.audioContext) {
  51076. this.stop(0);
  51077. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  51078. }
  51079. }
  51080. };
  51081. Sound.prototype.setVolume = function (newVolume, time) {
  51082. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  51083. if (time && BABYLON.Engine.audioEngine.audioContext) {
  51084. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  51085. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  51086. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  51087. }
  51088. else {
  51089. this._soundGain.gain.value = newVolume;
  51090. }
  51091. }
  51092. this._volume = newVolume;
  51093. };
  51094. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  51095. this._playbackRate = newPlaybackRate;
  51096. if (this.isPlaying) {
  51097. if (this._streaming) {
  51098. this._htmlAudioElement.playbackRate = this._playbackRate;
  51099. }
  51100. else if (this._soundSource) {
  51101. this._soundSource.playbackRate.value = this._playbackRate;
  51102. }
  51103. }
  51104. };
  51105. Sound.prototype.getVolume = function () {
  51106. return this._volume;
  51107. };
  51108. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  51109. var _this = this;
  51110. if (this._connectedMesh && this._registerFunc) {
  51111. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  51112. this._registerFunc = null;
  51113. }
  51114. this._connectedMesh = meshToConnectTo;
  51115. if (!this.spatialSound) {
  51116. this.spatialSound = true;
  51117. this._createSpatialParameters();
  51118. if (this.isPlaying && this.loop) {
  51119. this.stop();
  51120. this.play();
  51121. }
  51122. }
  51123. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  51124. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  51125. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  51126. };
  51127. Sound.prototype.detachFromMesh = function () {
  51128. if (this._connectedMesh && this._registerFunc) {
  51129. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  51130. this._registerFunc = null;
  51131. this._connectedMesh = null;
  51132. }
  51133. };
  51134. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  51135. if (!node.getBoundingInfo) {
  51136. return;
  51137. }
  51138. var mesh = node;
  51139. var boundingInfo = mesh.getBoundingInfo();
  51140. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  51141. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  51142. this._updateDirection();
  51143. }
  51144. };
  51145. Sound.prototype.clone = function () {
  51146. var _this = this;
  51147. if (!this._streaming) {
  51148. var setBufferAndRun = function () {
  51149. if (_this._isReadyToPlay) {
  51150. clonedSound._audioBuffer = _this.getAudioBuffer();
  51151. clonedSound._isReadyToPlay = true;
  51152. if (clonedSound.autoplay) {
  51153. clonedSound.play();
  51154. }
  51155. }
  51156. else {
  51157. window.setTimeout(setBufferAndRun, 300);
  51158. }
  51159. };
  51160. var currentOptions = {
  51161. autoplay: this.autoplay, loop: this.loop,
  51162. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  51163. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  51164. refDistance: this.refDistance, distanceModel: this.distanceModel
  51165. };
  51166. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  51167. if (this.useCustomAttenuation) {
  51168. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  51169. }
  51170. clonedSound.setPosition(this._position);
  51171. clonedSound.setPlaybackRate(this._playbackRate);
  51172. setBufferAndRun();
  51173. return clonedSound;
  51174. }
  51175. else {
  51176. return null;
  51177. }
  51178. };
  51179. Sound.prototype.getAudioBuffer = function () {
  51180. return this._audioBuffer;
  51181. };
  51182. Sound.prototype.serialize = function () {
  51183. var serializationObject = {
  51184. name: this.name,
  51185. url: this.name,
  51186. autoplay: this.autoplay,
  51187. loop: this.loop,
  51188. volume: this._volume,
  51189. spatialSound: this.spatialSound,
  51190. maxDistance: this.maxDistance,
  51191. rolloffFactor: this.rolloffFactor,
  51192. refDistance: this.refDistance,
  51193. distanceModel: this.distanceModel,
  51194. playbackRate: this._playbackRate,
  51195. panningModel: this._panningModel,
  51196. soundTrackId: this.soundTrackId
  51197. };
  51198. if (this.spatialSound) {
  51199. if (this._connectedMesh)
  51200. serializationObject.connectedMeshId = this._connectedMesh.id;
  51201. serializationObject.position = this._position.asArray();
  51202. serializationObject.refDistance = this.refDistance;
  51203. serializationObject.distanceModel = this.distanceModel;
  51204. serializationObject.isDirectional = this._isDirectional;
  51205. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  51206. serializationObject.coneInnerAngle = this._coneInnerAngle;
  51207. serializationObject.coneOuterAngle = this._coneOuterAngle;
  51208. serializationObject.coneOuterGain = this._coneOuterGain;
  51209. }
  51210. return serializationObject;
  51211. };
  51212. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  51213. var soundName = parsedSound.name;
  51214. var soundUrl;
  51215. if (parsedSound.url) {
  51216. soundUrl = rootUrl + parsedSound.url;
  51217. }
  51218. else {
  51219. soundUrl = rootUrl + soundName;
  51220. }
  51221. var options = {
  51222. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  51223. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  51224. rolloffFactor: parsedSound.rolloffFactor,
  51225. refDistance: parsedSound.refDistance,
  51226. distanceModel: parsedSound.distanceModel,
  51227. playbackRate: parsedSound.playbackRate
  51228. };
  51229. var newSound;
  51230. if (!sourceSound) {
  51231. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  51232. scene._addPendingData(newSound);
  51233. }
  51234. else {
  51235. var setBufferAndRun = function () {
  51236. if (sourceSound._isReadyToPlay) {
  51237. newSound._audioBuffer = sourceSound.getAudioBuffer();
  51238. newSound._isReadyToPlay = true;
  51239. if (newSound.autoplay) {
  51240. newSound.play();
  51241. }
  51242. }
  51243. else {
  51244. window.setTimeout(setBufferAndRun, 300);
  51245. }
  51246. };
  51247. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  51248. setBufferAndRun();
  51249. }
  51250. if (parsedSound.position) {
  51251. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  51252. newSound.setPosition(soundPosition);
  51253. }
  51254. if (parsedSound.isDirectional) {
  51255. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  51256. if (parsedSound.localDirectionToMesh) {
  51257. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  51258. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  51259. }
  51260. }
  51261. if (parsedSound.connectedMeshId) {
  51262. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  51263. if (connectedMesh) {
  51264. newSound.attachToMesh(connectedMesh);
  51265. }
  51266. }
  51267. return newSound;
  51268. };
  51269. return Sound;
  51270. }());
  51271. BABYLON.Sound = Sound;
  51272. })(BABYLON || (BABYLON = {}));
  51273. //# sourceMappingURL=babylon.sound.js.map
  51274. var BABYLON;
  51275. (function (BABYLON) {
  51276. var SoundTrack = /** @class */ (function () {
  51277. function SoundTrack(scene, options) {
  51278. this.id = -1;
  51279. this._isMainTrack = false;
  51280. this._isInitialized = false;
  51281. this._scene = scene;
  51282. this.soundCollection = new Array();
  51283. this._options = options;
  51284. if (!this._isMainTrack) {
  51285. this._scene.soundTracks.push(this);
  51286. this.id = this._scene.soundTracks.length - 1;
  51287. }
  51288. }
  51289. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  51290. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  51291. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  51292. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  51293. if (this._options) {
  51294. if (this._options.volume) {
  51295. this._outputAudioNode.gain.value = this._options.volume;
  51296. }
  51297. if (this._options.mainTrack) {
  51298. this._isMainTrack = this._options.mainTrack;
  51299. }
  51300. }
  51301. this._isInitialized = true;
  51302. }
  51303. };
  51304. SoundTrack.prototype.dispose = function () {
  51305. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51306. if (this._connectedAnalyser) {
  51307. this._connectedAnalyser.stopDebugCanvas();
  51308. }
  51309. while (this.soundCollection.length) {
  51310. this.soundCollection[0].dispose();
  51311. }
  51312. if (this._outputAudioNode) {
  51313. this._outputAudioNode.disconnect();
  51314. }
  51315. this._outputAudioNode = null;
  51316. }
  51317. };
  51318. SoundTrack.prototype.AddSound = function (sound) {
  51319. if (!this._isInitialized) {
  51320. this._initializeSoundTrackAudioGraph();
  51321. }
  51322. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51323. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  51324. }
  51325. if (sound.soundTrackId) {
  51326. if (sound.soundTrackId === -1) {
  51327. this._scene.mainSoundTrack.RemoveSound(sound);
  51328. }
  51329. else {
  51330. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  51331. }
  51332. }
  51333. this.soundCollection.push(sound);
  51334. sound.soundTrackId = this.id;
  51335. };
  51336. SoundTrack.prototype.RemoveSound = function (sound) {
  51337. var index = this.soundCollection.indexOf(sound);
  51338. if (index !== -1) {
  51339. this.soundCollection.splice(index, 1);
  51340. }
  51341. };
  51342. SoundTrack.prototype.setVolume = function (newVolume) {
  51343. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51344. this._outputAudioNode.gain.value = newVolume;
  51345. }
  51346. };
  51347. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  51348. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51349. for (var i = 0; i < this.soundCollection.length; i++) {
  51350. this.soundCollection[i].switchPanningModelToHRTF();
  51351. }
  51352. }
  51353. };
  51354. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  51355. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51356. for (var i = 0; i < this.soundCollection.length; i++) {
  51357. this.soundCollection[i].switchPanningModelToEqualPower();
  51358. }
  51359. }
  51360. };
  51361. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  51362. if (this._connectedAnalyser) {
  51363. this._connectedAnalyser.stopDebugCanvas();
  51364. }
  51365. this._connectedAnalyser = analyser;
  51366. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51367. this._outputAudioNode.disconnect();
  51368. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  51369. }
  51370. };
  51371. return SoundTrack;
  51372. }());
  51373. BABYLON.SoundTrack = SoundTrack;
  51374. })(BABYLON || (BABYLON = {}));
  51375. //# sourceMappingURL=babylon.soundtrack.js.map
  51376. var BABYLON;
  51377. (function (BABYLON) {
  51378. var Analyser = /** @class */ (function () {
  51379. function Analyser(scene) {
  51380. this.SMOOTHING = 0.75;
  51381. this.FFT_SIZE = 512;
  51382. this.BARGRAPHAMPLITUDE = 256;
  51383. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  51384. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  51385. this._scene = scene;
  51386. this._audioEngine = BABYLON.Engine.audioEngine;
  51387. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  51388. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  51389. this._webAudioAnalyser.minDecibels = -140;
  51390. this._webAudioAnalyser.maxDecibels = 0;
  51391. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51392. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51393. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  51394. }
  51395. }
  51396. Analyser.prototype.getFrequencyBinCount = function () {
  51397. if (this._audioEngine.canUseWebAudio) {
  51398. return this._webAudioAnalyser.frequencyBinCount;
  51399. }
  51400. else {
  51401. return 0;
  51402. }
  51403. };
  51404. Analyser.prototype.getByteFrequencyData = function () {
  51405. if (this._audioEngine.canUseWebAudio) {
  51406. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51407. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51408. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  51409. }
  51410. return this._byteFreqs;
  51411. };
  51412. Analyser.prototype.getByteTimeDomainData = function () {
  51413. if (this._audioEngine.canUseWebAudio) {
  51414. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51415. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51416. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  51417. }
  51418. return this._byteTime;
  51419. };
  51420. Analyser.prototype.getFloatFrequencyData = function () {
  51421. if (this._audioEngine.canUseWebAudio) {
  51422. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51423. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51424. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  51425. }
  51426. return this._floatFreqs;
  51427. };
  51428. Analyser.prototype.drawDebugCanvas = function () {
  51429. var _this = this;
  51430. if (this._audioEngine.canUseWebAudio) {
  51431. if (!this._debugCanvas) {
  51432. this._debugCanvas = document.createElement("canvas");
  51433. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  51434. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  51435. this._debugCanvas.style.position = "absolute";
  51436. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  51437. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  51438. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  51439. document.body.appendChild(this._debugCanvas);
  51440. this._registerFunc = function () {
  51441. _this.drawDebugCanvas();
  51442. };
  51443. this._scene.registerBeforeRender(this._registerFunc);
  51444. }
  51445. if (this._registerFunc && this._debugCanvasContext) {
  51446. var workingArray = this.getByteFrequencyData();
  51447. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  51448. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  51449. // Draw the frequency domain chart.
  51450. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  51451. var value = workingArray[i];
  51452. var percent = value / this.BARGRAPHAMPLITUDE;
  51453. var height = this.DEBUGCANVASSIZE.height * percent;
  51454. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  51455. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  51456. var hue = i / this.getFrequencyBinCount() * 360;
  51457. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  51458. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  51459. }
  51460. }
  51461. }
  51462. };
  51463. Analyser.prototype.stopDebugCanvas = function () {
  51464. if (this._debugCanvas) {
  51465. if (this._registerFunc) {
  51466. this._scene.unregisterBeforeRender(this._registerFunc);
  51467. this._registerFunc = null;
  51468. }
  51469. document.body.removeChild(this._debugCanvas);
  51470. this._debugCanvas = null;
  51471. this._debugCanvasContext = null;
  51472. }
  51473. };
  51474. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  51475. if (this._audioEngine.canUseWebAudio) {
  51476. inputAudioNode.connect(this._webAudioAnalyser);
  51477. this._webAudioAnalyser.connect(outputAudioNode);
  51478. }
  51479. };
  51480. Analyser.prototype.dispose = function () {
  51481. if (this._audioEngine.canUseWebAudio) {
  51482. this._webAudioAnalyser.disconnect();
  51483. }
  51484. };
  51485. return Analyser;
  51486. }());
  51487. BABYLON.Analyser = Analyser;
  51488. })(BABYLON || (BABYLON = {}));
  51489. //# sourceMappingURL=babylon.analyser.js.map
  51490. var BABYLON;
  51491. (function (BABYLON) {
  51492. var CubeTexture = /** @class */ (function (_super) {
  51493. __extends(CubeTexture, _super);
  51494. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  51495. if (extensions === void 0) { extensions = null; }
  51496. if (noMipmap === void 0) { noMipmap = false; }
  51497. if (files === void 0) { files = null; }
  51498. if (onLoad === void 0) { onLoad = null; }
  51499. if (onError === void 0) { onError = null; }
  51500. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  51501. if (prefiltered === void 0) { prefiltered = false; }
  51502. if (forcedExtension === void 0) { forcedExtension = null; }
  51503. var _this = _super.call(this, scene) || this;
  51504. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51505. _this.name = rootUrl;
  51506. _this.url = rootUrl;
  51507. _this._noMipmap = noMipmap;
  51508. _this.hasAlpha = false;
  51509. _this._format = format;
  51510. _this._prefiltered = prefiltered;
  51511. _this.isCube = true;
  51512. _this._textureMatrix = BABYLON.Matrix.Identity();
  51513. if (prefiltered) {
  51514. _this.gammaSpace = false;
  51515. }
  51516. if (!rootUrl && !files) {
  51517. return _this;
  51518. }
  51519. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  51520. var lastDot = rootUrl.lastIndexOf(".");
  51521. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  51522. var isDDS = (extension === ".dds");
  51523. if (!files) {
  51524. if (!isDDS && !extensions) {
  51525. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  51526. }
  51527. files = [];
  51528. if (extensions) {
  51529. for (var index = 0; index < extensions.length; index++) {
  51530. files.push(rootUrl + extensions[index]);
  51531. }
  51532. }
  51533. }
  51534. _this._files = files;
  51535. if (!_this._texture) {
  51536. if (!scene.useDelayedTextureLoading) {
  51537. if (prefiltered) {
  51538. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  51539. }
  51540. else {
  51541. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  51542. }
  51543. }
  51544. else {
  51545. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51546. }
  51547. }
  51548. else if (onLoad) {
  51549. if (_this._texture.isReady) {
  51550. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  51551. }
  51552. else {
  51553. _this._texture.onLoadedObservable.add(onLoad);
  51554. }
  51555. }
  51556. return _this;
  51557. }
  51558. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  51559. return new CubeTexture("", scene, null, noMipmap, files);
  51560. };
  51561. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  51562. if (forcedExtension === void 0) { forcedExtension = null; }
  51563. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  51564. };
  51565. // Methods
  51566. CubeTexture.prototype.delayLoad = function () {
  51567. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51568. return;
  51569. }
  51570. var scene = this.getScene();
  51571. if (!scene) {
  51572. return;
  51573. }
  51574. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51575. this._texture = this._getFromCache(this.url, this._noMipmap);
  51576. if (!this._texture) {
  51577. if (this._prefiltered) {
  51578. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  51579. }
  51580. else {
  51581. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  51582. }
  51583. }
  51584. };
  51585. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  51586. return this._textureMatrix;
  51587. };
  51588. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  51589. this._textureMatrix = value;
  51590. };
  51591. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51592. var texture = BABYLON.SerializationHelper.Parse(function () {
  51593. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  51594. }, parsedTexture, scene);
  51595. // Animations
  51596. if (parsedTexture.animations) {
  51597. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  51598. var parsedAnimation = parsedTexture.animations[animationIndex];
  51599. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51600. }
  51601. }
  51602. return texture;
  51603. };
  51604. CubeTexture.prototype.clone = function () {
  51605. var _this = this;
  51606. return BABYLON.SerializationHelper.Clone(function () {
  51607. var scene = _this.getScene();
  51608. if (!scene) {
  51609. return _this;
  51610. }
  51611. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  51612. }, this);
  51613. };
  51614. return CubeTexture;
  51615. }(BABYLON.BaseTexture));
  51616. BABYLON.CubeTexture = CubeTexture;
  51617. })(BABYLON || (BABYLON = {}));
  51618. //# sourceMappingURL=babylon.cubeTexture.js.map
  51619. var BABYLON;
  51620. (function (BABYLON) {
  51621. var RenderTargetTexture = /** @class */ (function (_super) {
  51622. __extends(RenderTargetTexture, _super);
  51623. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  51624. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  51625. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51626. if (isCube === void 0) { isCube = false; }
  51627. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51628. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  51629. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  51630. if (isMulti === void 0) { isMulti = false; }
  51631. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  51632. _this.isCube = isCube;
  51633. /**
  51634. * Use this list to define the list of mesh you want to render.
  51635. */
  51636. _this.renderList = new Array();
  51637. _this.renderParticles = true;
  51638. _this.renderSprites = false;
  51639. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  51640. _this.ignoreCameraViewport = false;
  51641. // Events
  51642. /**
  51643. * An event triggered when the texture is unbind.
  51644. * @type {BABYLON.Observable}
  51645. */
  51646. _this.onBeforeBindObservable = new BABYLON.Observable();
  51647. /**
  51648. * An event triggered when the texture is unbind.
  51649. * @type {BABYLON.Observable}
  51650. */
  51651. _this.onAfterUnbindObservable = new BABYLON.Observable();
  51652. /**
  51653. * An event triggered before rendering the texture
  51654. * @type {BABYLON.Observable}
  51655. */
  51656. _this.onBeforeRenderObservable = new BABYLON.Observable();
  51657. /**
  51658. * An event triggered after rendering the texture
  51659. * @type {BABYLON.Observable}
  51660. */
  51661. _this.onAfterRenderObservable = new BABYLON.Observable();
  51662. /**
  51663. * An event triggered after the texture clear
  51664. * @type {BABYLON.Observable}
  51665. */
  51666. _this.onClearObservable = new BABYLON.Observable();
  51667. _this._currentRefreshId = -1;
  51668. _this._refreshRate = 1;
  51669. _this._samples = 1;
  51670. scene = _this.getScene();
  51671. if (!scene) {
  51672. return _this;
  51673. }
  51674. _this._engine = scene.getEngine();
  51675. _this.name = name;
  51676. _this.isRenderTarget = true;
  51677. _this._initialSizeParameter = size;
  51678. _this._processSizeParameter(size);
  51679. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  51680. });
  51681. _this._generateMipMaps = generateMipMaps ? true : false;
  51682. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  51683. // Rendering groups
  51684. _this._renderingManager = new BABYLON.RenderingManager(scene);
  51685. if (isMulti) {
  51686. return _this;
  51687. }
  51688. _this._renderTargetOptions = {
  51689. generateMipMaps: generateMipMaps,
  51690. type: type,
  51691. samplingMode: samplingMode,
  51692. generateDepthBuffer: generateDepthBuffer,
  51693. generateStencilBuffer: generateStencilBuffer
  51694. };
  51695. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  51696. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51697. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51698. }
  51699. if (isCube) {
  51700. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  51701. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  51702. _this._textureMatrix = BABYLON.Matrix.Identity();
  51703. }
  51704. else {
  51705. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  51706. }
  51707. return _this;
  51708. }
  51709. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  51710. get: function () {
  51711. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  51712. },
  51713. enumerable: true,
  51714. configurable: true
  51715. });
  51716. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  51717. get: function () {
  51718. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  51719. },
  51720. enumerable: true,
  51721. configurable: true
  51722. });
  51723. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  51724. get: function () {
  51725. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  51726. },
  51727. enumerable: true,
  51728. configurable: true
  51729. });
  51730. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  51731. set: function (callback) {
  51732. if (this._onAfterUnbindObserver) {
  51733. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  51734. }
  51735. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  51736. },
  51737. enumerable: true,
  51738. configurable: true
  51739. });
  51740. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  51741. set: function (callback) {
  51742. if (this._onBeforeRenderObserver) {
  51743. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  51744. }
  51745. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  51746. },
  51747. enumerable: true,
  51748. configurable: true
  51749. });
  51750. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  51751. set: function (callback) {
  51752. if (this._onAfterRenderObserver) {
  51753. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  51754. }
  51755. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  51756. },
  51757. enumerable: true,
  51758. configurable: true
  51759. });
  51760. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  51761. set: function (callback) {
  51762. if (this._onClearObserver) {
  51763. this.onClearObservable.remove(this._onClearObserver);
  51764. }
  51765. this._onClearObserver = this.onClearObservable.add(callback);
  51766. },
  51767. enumerable: true,
  51768. configurable: true
  51769. });
  51770. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  51771. get: function () {
  51772. return this._renderTargetOptions;
  51773. },
  51774. enumerable: true,
  51775. configurable: true
  51776. });
  51777. RenderTargetTexture.prototype._onRatioRescale = function () {
  51778. if (this._sizeRatio) {
  51779. this.resize(this._initialSizeParameter);
  51780. }
  51781. };
  51782. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  51783. if (size.ratio) {
  51784. this._sizeRatio = size.ratio;
  51785. this._size = {
  51786. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  51787. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  51788. };
  51789. }
  51790. else {
  51791. this._size = size;
  51792. }
  51793. };
  51794. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  51795. get: function () {
  51796. return this._samples;
  51797. },
  51798. set: function (value) {
  51799. if (this._samples === value) {
  51800. return;
  51801. }
  51802. var scene = this.getScene();
  51803. if (!scene) {
  51804. return;
  51805. }
  51806. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  51807. },
  51808. enumerable: true,
  51809. configurable: true
  51810. });
  51811. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  51812. this._currentRefreshId = -1;
  51813. };
  51814. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  51815. get: function () {
  51816. return this._refreshRate;
  51817. },
  51818. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  51819. set: function (value) {
  51820. this._refreshRate = value;
  51821. this.resetRefreshCounter();
  51822. },
  51823. enumerable: true,
  51824. configurable: true
  51825. });
  51826. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  51827. if (!this._postProcessManager) {
  51828. var scene = this.getScene();
  51829. if (!scene) {
  51830. return;
  51831. }
  51832. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  51833. this._postProcesses = new Array();
  51834. }
  51835. this._postProcesses.push(postProcess);
  51836. this._postProcesses[0].autoClear = false;
  51837. };
  51838. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  51839. if (!this._postProcesses) {
  51840. return;
  51841. }
  51842. if (dispose) {
  51843. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  51844. var postProcess = _a[_i];
  51845. postProcess.dispose();
  51846. }
  51847. }
  51848. this._postProcesses = [];
  51849. };
  51850. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  51851. if (!this._postProcesses) {
  51852. return;
  51853. }
  51854. var index = this._postProcesses.indexOf(postProcess);
  51855. if (index === -1) {
  51856. return;
  51857. }
  51858. this._postProcesses.splice(index, 1);
  51859. if (this._postProcesses.length > 0) {
  51860. this._postProcesses[0].autoClear = false;
  51861. }
  51862. };
  51863. RenderTargetTexture.prototype._shouldRender = function () {
  51864. if (this._currentRefreshId === -1) {
  51865. this._currentRefreshId = 1;
  51866. return true;
  51867. }
  51868. if (this.refreshRate === this._currentRefreshId) {
  51869. this._currentRefreshId = 1;
  51870. return true;
  51871. }
  51872. this._currentRefreshId++;
  51873. return false;
  51874. };
  51875. RenderTargetTexture.prototype.getRenderSize = function () {
  51876. if (this._size.width) {
  51877. return this._size.width;
  51878. }
  51879. return this._size;
  51880. };
  51881. RenderTargetTexture.prototype.getRenderWidth = function () {
  51882. if (this._size.width) {
  51883. return this._size.width;
  51884. }
  51885. return this._size;
  51886. };
  51887. RenderTargetTexture.prototype.getRenderHeight = function () {
  51888. if (this._size.width) {
  51889. return this._size.height;
  51890. }
  51891. return this._size;
  51892. };
  51893. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  51894. get: function () {
  51895. return true;
  51896. },
  51897. enumerable: true,
  51898. configurable: true
  51899. });
  51900. RenderTargetTexture.prototype.scale = function (ratio) {
  51901. var newSize = this.getRenderSize() * ratio;
  51902. this.resize(newSize);
  51903. };
  51904. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  51905. if (this.isCube) {
  51906. return this._textureMatrix;
  51907. }
  51908. return _super.prototype.getReflectionTextureMatrix.call(this);
  51909. };
  51910. RenderTargetTexture.prototype.resize = function (size) {
  51911. this.releaseInternalTexture();
  51912. var scene = this.getScene();
  51913. if (!scene) {
  51914. return;
  51915. }
  51916. this._processSizeParameter(size);
  51917. if (this.isCube) {
  51918. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  51919. }
  51920. else {
  51921. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  51922. }
  51923. };
  51924. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  51925. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  51926. if (dumpForDebug === void 0) { dumpForDebug = false; }
  51927. var scene = this.getScene();
  51928. if (!scene) {
  51929. return;
  51930. }
  51931. var engine = scene.getEngine();
  51932. if (this.useCameraPostProcesses !== undefined) {
  51933. useCameraPostProcess = this.useCameraPostProcesses;
  51934. }
  51935. if (this._waitingRenderList) {
  51936. this.renderList = [];
  51937. for (var index = 0; index < this._waitingRenderList.length; index++) {
  51938. var id = this._waitingRenderList[index];
  51939. var mesh_1 = scene.getMeshByID(id);
  51940. if (mesh_1) {
  51941. this.renderList.push(mesh_1);
  51942. }
  51943. }
  51944. delete this._waitingRenderList;
  51945. }
  51946. // Is predicate defined?
  51947. if (this.renderListPredicate) {
  51948. if (this.renderList) {
  51949. this.renderList.splice(0); // Clear previous renderList
  51950. }
  51951. else {
  51952. this.renderList = [];
  51953. }
  51954. var scene = this.getScene();
  51955. if (!scene) {
  51956. return;
  51957. }
  51958. var sceneMeshes = scene.meshes;
  51959. for (var index = 0; index < sceneMeshes.length; index++) {
  51960. var mesh = sceneMeshes[index];
  51961. if (this.renderListPredicate(mesh)) {
  51962. this.renderList.push(mesh);
  51963. }
  51964. }
  51965. }
  51966. this.onBeforeBindObservable.notifyObservers(this);
  51967. // Set custom projection.
  51968. // Needs to be before binding to prevent changing the aspect ratio.
  51969. var camera;
  51970. if (this.activeCamera) {
  51971. camera = this.activeCamera;
  51972. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  51973. if (this.activeCamera !== scene.activeCamera) {
  51974. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  51975. }
  51976. }
  51977. else {
  51978. camera = scene.activeCamera;
  51979. if (camera) {
  51980. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  51981. }
  51982. }
  51983. // Prepare renderingManager
  51984. this._renderingManager.reset();
  51985. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  51986. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  51987. var sceneRenderId = scene.getRenderId();
  51988. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  51989. var mesh = currentRenderList[meshIndex];
  51990. if (mesh) {
  51991. if (!mesh.isReady()) {
  51992. // Reset _currentRefreshId
  51993. this.resetRefreshCounter();
  51994. continue;
  51995. }
  51996. mesh._preActivateForIntermediateRendering(sceneRenderId);
  51997. var isMasked = void 0;
  51998. if (!this.renderList && camera) {
  51999. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  52000. }
  52001. else {
  52002. isMasked = false;
  52003. }
  52004. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  52005. mesh._activate(sceneRenderId);
  52006. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  52007. var subMesh = mesh.subMeshes[subIndex];
  52008. scene._activeIndices.addCount(subMesh.indexCount, false);
  52009. this._renderingManager.dispatch(subMesh, mesh);
  52010. }
  52011. }
  52012. }
  52013. }
  52014. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  52015. var particleSystem = scene.particleSystems[particleIndex];
  52016. var emitter = particleSystem.emitter;
  52017. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  52018. continue;
  52019. }
  52020. if (currentRenderList.indexOf(emitter) >= 0) {
  52021. this._renderingManager.dispatchParticles(particleSystem);
  52022. }
  52023. }
  52024. if (this.isCube) {
  52025. for (var face = 0; face < 6; face++) {
  52026. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  52027. scene.incrementRenderId();
  52028. scene.resetCachedMaterial();
  52029. }
  52030. }
  52031. else {
  52032. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  52033. }
  52034. this.onAfterUnbindObservable.notifyObservers(this);
  52035. if (scene.activeCamera) {
  52036. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  52037. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  52038. }
  52039. engine.setViewport(scene.activeCamera.viewport);
  52040. }
  52041. scene.resetCachedMaterial();
  52042. };
  52043. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  52044. var minimum = 128;
  52045. var x = renderDimension * scale;
  52046. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  52047. // Ensure we don't exceed the render dimension (while staying POT)
  52048. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  52049. };
  52050. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  52051. var _this = this;
  52052. if (!this._texture) {
  52053. return;
  52054. }
  52055. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  52056. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  52057. });
  52058. };
  52059. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  52060. var scene = this.getScene();
  52061. if (!scene) {
  52062. return;
  52063. }
  52064. var engine = scene.getEngine();
  52065. if (!this._texture) {
  52066. return;
  52067. }
  52068. // Bind
  52069. if (this._postProcessManager) {
  52070. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  52071. }
  52072. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  52073. if (this._texture) {
  52074. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  52075. }
  52076. }
  52077. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  52078. // Clear
  52079. if (this.onClearObservable.hasObservers()) {
  52080. this.onClearObservable.notifyObservers(engine);
  52081. }
  52082. else {
  52083. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  52084. }
  52085. if (!this._doNotChangeAspectRatio) {
  52086. scene.updateTransformMatrix(true);
  52087. }
  52088. // Render
  52089. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  52090. if (this._postProcessManager) {
  52091. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  52092. }
  52093. else if (useCameraPostProcess) {
  52094. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  52095. }
  52096. if (!this._doNotChangeAspectRatio) {
  52097. scene.updateTransformMatrix(true);
  52098. }
  52099. // Dump ?
  52100. if (dumpForDebug) {
  52101. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  52102. }
  52103. // Unbind
  52104. if (!this.isCube || faceIndex === 5) {
  52105. if (this.isCube) {
  52106. if (faceIndex === 5) {
  52107. engine.generateMipMapsForCubemap(this._texture);
  52108. }
  52109. }
  52110. this.unbindFrameBuffer(engine, faceIndex);
  52111. }
  52112. else {
  52113. this.onAfterRenderObservable.notifyObservers(faceIndex);
  52114. }
  52115. };
  52116. /**
  52117. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  52118. * This allowed control for front to back rendering or reversly depending of the special needs.
  52119. *
  52120. * @param renderingGroupId The rendering group id corresponding to its index
  52121. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  52122. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  52123. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  52124. */
  52125. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  52126. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  52127. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  52128. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  52129. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  52130. };
  52131. /**
  52132. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  52133. *
  52134. * @param renderingGroupId The rendering group id corresponding to its index
  52135. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  52136. */
  52137. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  52138. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  52139. };
  52140. RenderTargetTexture.prototype.clone = function () {
  52141. var textureSize = this.getSize();
  52142. 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);
  52143. // Base texture
  52144. newTexture.hasAlpha = this.hasAlpha;
  52145. newTexture.level = this.level;
  52146. // RenderTarget Texture
  52147. newTexture.coordinatesMode = this.coordinatesMode;
  52148. if (this.renderList) {
  52149. newTexture.renderList = this.renderList.slice(0);
  52150. }
  52151. return newTexture;
  52152. };
  52153. RenderTargetTexture.prototype.serialize = function () {
  52154. if (!this.name) {
  52155. return null;
  52156. }
  52157. var serializationObject = _super.prototype.serialize.call(this);
  52158. serializationObject.renderTargetSize = this.getRenderSize();
  52159. serializationObject.renderList = [];
  52160. if (this.renderList) {
  52161. for (var index = 0; index < this.renderList.length; index++) {
  52162. serializationObject.renderList.push(this.renderList[index].id);
  52163. }
  52164. }
  52165. return serializationObject;
  52166. };
  52167. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  52168. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  52169. var objBuffer = this.getInternalTexture();
  52170. var scene = this.getScene();
  52171. if (objBuffer && scene) {
  52172. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  52173. }
  52174. };
  52175. RenderTargetTexture.prototype.dispose = function () {
  52176. if (this._postProcessManager) {
  52177. this._postProcessManager.dispose();
  52178. this._postProcessManager = null;
  52179. }
  52180. this.clearPostProcesses(true);
  52181. if (this._resizeObserver) {
  52182. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  52183. this._resizeObserver = null;
  52184. }
  52185. this.renderList = null;
  52186. // Remove from custom render targets
  52187. var scene = this.getScene();
  52188. if (!scene) {
  52189. return;
  52190. }
  52191. var index = scene.customRenderTargets.indexOf(this);
  52192. if (index >= 0) {
  52193. scene.customRenderTargets.splice(index, 1);
  52194. }
  52195. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  52196. var camera = _a[_i];
  52197. index = camera.customRenderTargets.indexOf(this);
  52198. if (index >= 0) {
  52199. camera.customRenderTargets.splice(index, 1);
  52200. }
  52201. }
  52202. _super.prototype.dispose.call(this);
  52203. };
  52204. RenderTargetTexture.prototype._rebuild = function () {
  52205. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  52206. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  52207. }
  52208. if (this._postProcessManager) {
  52209. this._postProcessManager._rebuild();
  52210. }
  52211. };
  52212. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  52213. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  52214. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  52215. return RenderTargetTexture;
  52216. }(BABYLON.Texture));
  52217. BABYLON.RenderTargetTexture = RenderTargetTexture;
  52218. })(BABYLON || (BABYLON = {}));
  52219. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  52220. var BABYLON;
  52221. (function (BABYLON) {
  52222. ;
  52223. var MultiRenderTarget = /** @class */ (function (_super) {
  52224. __extends(MultiRenderTarget, _super);
  52225. function MultiRenderTarget(name, size, count, scene, options) {
  52226. var _this = this;
  52227. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  52228. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  52229. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  52230. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  52231. _this._engine = scene.getEngine();
  52232. if (!_this.isSupported) {
  52233. _this.dispose();
  52234. return;
  52235. }
  52236. var types = [];
  52237. var samplingModes = [];
  52238. for (var i = 0; i < count; i++) {
  52239. if (options && options.types && options.types[i] !== undefined) {
  52240. types.push(options.types[i]);
  52241. }
  52242. else {
  52243. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52244. }
  52245. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  52246. samplingModes.push(options.samplingModes[i]);
  52247. }
  52248. else {
  52249. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52250. }
  52251. }
  52252. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  52253. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  52254. _this._size = size;
  52255. _this._multiRenderTargetOptions = {
  52256. samplingModes: samplingModes,
  52257. generateMipMaps: generateMipMaps,
  52258. generateDepthBuffer: generateDepthBuffer,
  52259. generateStencilBuffer: generateStencilBuffer,
  52260. generateDepthTexture: generateDepthTexture,
  52261. types: types,
  52262. textureCount: count
  52263. };
  52264. _this._createInternalTextures();
  52265. _this._createTextures();
  52266. return _this;
  52267. }
  52268. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  52269. get: function () {
  52270. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  52271. },
  52272. enumerable: true,
  52273. configurable: true
  52274. });
  52275. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  52276. get: function () {
  52277. return this._textures;
  52278. },
  52279. enumerable: true,
  52280. configurable: true
  52281. });
  52282. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  52283. get: function () {
  52284. return this._textures[this._textures.length - 1];
  52285. },
  52286. enumerable: true,
  52287. configurable: true
  52288. });
  52289. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  52290. set: function (wrap) {
  52291. if (this._textures) {
  52292. for (var i = 0; i < this._textures.length; i++) {
  52293. this._textures[i].wrapU = wrap;
  52294. }
  52295. }
  52296. },
  52297. enumerable: true,
  52298. configurable: true
  52299. });
  52300. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  52301. set: function (wrap) {
  52302. if (this._textures) {
  52303. for (var i = 0; i < this._textures.length; i++) {
  52304. this._textures[i].wrapV = wrap;
  52305. }
  52306. }
  52307. },
  52308. enumerable: true,
  52309. configurable: true
  52310. });
  52311. MultiRenderTarget.prototype._rebuild = function () {
  52312. this.releaseInternalTextures();
  52313. this._createInternalTextures();
  52314. for (var i = 0; i < this._internalTextures.length; i++) {
  52315. var texture = this._textures[i];
  52316. texture._texture = this._internalTextures[i];
  52317. }
  52318. // Keeps references to frame buffer and stencil/depth buffer
  52319. this._texture = this._internalTextures[0];
  52320. };
  52321. MultiRenderTarget.prototype._createInternalTextures = function () {
  52322. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  52323. };
  52324. MultiRenderTarget.prototype._createTextures = function () {
  52325. this._textures = [];
  52326. for (var i = 0; i < this._internalTextures.length; i++) {
  52327. var texture = new BABYLON.Texture(null, this.getScene());
  52328. texture._texture = this._internalTextures[i];
  52329. this._textures.push(texture);
  52330. }
  52331. // Keeps references to frame buffer and stencil/depth buffer
  52332. this._texture = this._internalTextures[0];
  52333. };
  52334. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  52335. get: function () {
  52336. return this._samples;
  52337. },
  52338. set: function (value) {
  52339. if (this._samples === value) {
  52340. return;
  52341. }
  52342. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  52343. },
  52344. enumerable: true,
  52345. configurable: true
  52346. });
  52347. MultiRenderTarget.prototype.resize = function (size) {
  52348. this.releaseInternalTextures();
  52349. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  52350. this._createInternalTextures();
  52351. };
  52352. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  52353. var _this = this;
  52354. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  52355. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  52356. });
  52357. };
  52358. MultiRenderTarget.prototype.dispose = function () {
  52359. this.releaseInternalTextures();
  52360. _super.prototype.dispose.call(this);
  52361. };
  52362. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  52363. if (!this._internalTextures) {
  52364. return;
  52365. }
  52366. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  52367. if (this._internalTextures[i] !== undefined) {
  52368. this._internalTextures[i].dispose();
  52369. this._internalTextures.splice(i, 1);
  52370. }
  52371. }
  52372. };
  52373. return MultiRenderTarget;
  52374. }(BABYLON.RenderTargetTexture));
  52375. BABYLON.MultiRenderTarget = MultiRenderTarget;
  52376. })(BABYLON || (BABYLON = {}));
  52377. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  52378. var BABYLON;
  52379. (function (BABYLON) {
  52380. var MirrorTexture = /** @class */ (function (_super) {
  52381. __extends(MirrorTexture, _super);
  52382. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  52383. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52384. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52385. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  52386. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  52387. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  52388. _this._transformMatrix = BABYLON.Matrix.Zero();
  52389. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  52390. _this._adaptiveBlurKernel = 0;
  52391. _this._blurKernelX = 0;
  52392. _this._blurKernelY = 0;
  52393. _this._blurRatio = 1.0;
  52394. _this.ignoreCameraViewport = true;
  52395. _this.onBeforeRenderObservable.add(function () {
  52396. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  52397. _this._savedViewMatrix = scene.getViewMatrix();
  52398. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  52399. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  52400. scene.clipPlane = _this.mirrorPlane;
  52401. scene.getEngine().cullBackFaces = false;
  52402. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  52403. });
  52404. _this.onAfterRenderObservable.add(function () {
  52405. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  52406. scene.getEngine().cullBackFaces = true;
  52407. scene._mirroredCameraPosition = null;
  52408. delete scene.clipPlane;
  52409. });
  52410. return _this;
  52411. }
  52412. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  52413. get: function () {
  52414. return this._blurRatio;
  52415. },
  52416. set: function (value) {
  52417. if (this._blurRatio === value) {
  52418. return;
  52419. }
  52420. this._blurRatio = value;
  52421. this._preparePostProcesses();
  52422. },
  52423. enumerable: true,
  52424. configurable: true
  52425. });
  52426. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  52427. set: function (value) {
  52428. this._adaptiveBlurKernel = value;
  52429. this._autoComputeBlurKernel();
  52430. },
  52431. enumerable: true,
  52432. configurable: true
  52433. });
  52434. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  52435. set: function (value) {
  52436. this.blurKernelX = value;
  52437. this.blurKernelY = value;
  52438. },
  52439. enumerable: true,
  52440. configurable: true
  52441. });
  52442. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  52443. get: function () {
  52444. return this._blurKernelX;
  52445. },
  52446. set: function (value) {
  52447. if (this._blurKernelX === value) {
  52448. return;
  52449. }
  52450. this._blurKernelX = value;
  52451. this._preparePostProcesses();
  52452. },
  52453. enumerable: true,
  52454. configurable: true
  52455. });
  52456. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  52457. get: function () {
  52458. return this._blurKernelY;
  52459. },
  52460. set: function (value) {
  52461. if (this._blurKernelY === value) {
  52462. return;
  52463. }
  52464. this._blurKernelY = value;
  52465. this._preparePostProcesses();
  52466. },
  52467. enumerable: true,
  52468. configurable: true
  52469. });
  52470. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  52471. var engine = this.getScene().getEngine();
  52472. var dw = this.getRenderWidth() / engine.getRenderWidth();
  52473. var dh = this.getRenderHeight() / engine.getRenderHeight();
  52474. this.blurKernelX = this._adaptiveBlurKernel * dw;
  52475. this.blurKernelY = this._adaptiveBlurKernel * dh;
  52476. };
  52477. MirrorTexture.prototype._onRatioRescale = function () {
  52478. if (this._sizeRatio) {
  52479. this.resize(this._initialSizeParameter);
  52480. if (!this._adaptiveBlurKernel) {
  52481. this._preparePostProcesses();
  52482. }
  52483. }
  52484. if (this._adaptiveBlurKernel) {
  52485. this._autoComputeBlurKernel();
  52486. }
  52487. };
  52488. MirrorTexture.prototype._preparePostProcesses = function () {
  52489. this.clearPostProcesses(true);
  52490. if (this._blurKernelX && this._blurKernelY) {
  52491. var engine = this.getScene().getEngine();
  52492. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52493. 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);
  52494. this._blurX.autoClear = false;
  52495. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  52496. this._blurX.outputTexture = this._texture;
  52497. }
  52498. else {
  52499. this._blurX.alwaysForcePOT = true;
  52500. }
  52501. 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);
  52502. this._blurY.autoClear = false;
  52503. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  52504. this.addPostProcess(this._blurX);
  52505. this.addPostProcess(this._blurY);
  52506. }
  52507. else {
  52508. if (this._blurY) {
  52509. this.removePostProcess(this._blurY);
  52510. this._blurY.dispose();
  52511. this._blurY = null;
  52512. }
  52513. if (this._blurX) {
  52514. this.removePostProcess(this._blurX);
  52515. this._blurX.dispose();
  52516. this._blurX = null;
  52517. }
  52518. }
  52519. };
  52520. MirrorTexture.prototype.clone = function () {
  52521. var scene = this.getScene();
  52522. if (!scene) {
  52523. return this;
  52524. }
  52525. var textureSize = this.getSize();
  52526. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  52527. // Base texture
  52528. newTexture.hasAlpha = this.hasAlpha;
  52529. newTexture.level = this.level;
  52530. // Mirror Texture
  52531. newTexture.mirrorPlane = this.mirrorPlane.clone();
  52532. if (this.renderList) {
  52533. newTexture.renderList = this.renderList.slice(0);
  52534. }
  52535. return newTexture;
  52536. };
  52537. MirrorTexture.prototype.serialize = function () {
  52538. if (!this.name) {
  52539. return null;
  52540. }
  52541. var serializationObject = _super.prototype.serialize.call(this);
  52542. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  52543. return serializationObject;
  52544. };
  52545. return MirrorTexture;
  52546. }(BABYLON.RenderTargetTexture));
  52547. BABYLON.MirrorTexture = MirrorTexture;
  52548. })(BABYLON || (BABYLON = {}));
  52549. //# sourceMappingURL=babylon.mirrorTexture.js.map
  52550. var BABYLON;
  52551. (function (BABYLON) {
  52552. /**
  52553. * Creates a refraction texture used by refraction channel of the standard material.
  52554. * @param name the texture name
  52555. * @param size size of the underlying texture
  52556. * @param scene root scene
  52557. */
  52558. var RefractionTexture = /** @class */ (function (_super) {
  52559. __extends(RefractionTexture, _super);
  52560. function RefractionTexture(name, size, scene, generateMipMaps) {
  52561. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  52562. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  52563. _this.depth = 2.0;
  52564. _this.onBeforeRenderObservable.add(function () {
  52565. scene.clipPlane = _this.refractionPlane;
  52566. });
  52567. _this.onAfterRenderObservable.add(function () {
  52568. delete scene.clipPlane;
  52569. });
  52570. return _this;
  52571. }
  52572. RefractionTexture.prototype.clone = function () {
  52573. var scene = this.getScene();
  52574. if (!scene) {
  52575. return this;
  52576. }
  52577. var textureSize = this.getSize();
  52578. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  52579. // Base texture
  52580. newTexture.hasAlpha = this.hasAlpha;
  52581. newTexture.level = this.level;
  52582. // Refraction Texture
  52583. newTexture.refractionPlane = this.refractionPlane.clone();
  52584. if (this.renderList) {
  52585. newTexture.renderList = this.renderList.slice(0);
  52586. }
  52587. newTexture.depth = this.depth;
  52588. return newTexture;
  52589. };
  52590. RefractionTexture.prototype.serialize = function () {
  52591. if (!this.name) {
  52592. return null;
  52593. }
  52594. var serializationObject = _super.prototype.serialize.call(this);
  52595. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  52596. serializationObject.depth = this.depth;
  52597. return serializationObject;
  52598. };
  52599. return RefractionTexture;
  52600. }(BABYLON.RenderTargetTexture));
  52601. BABYLON.RefractionTexture = RefractionTexture;
  52602. })(BABYLON || (BABYLON = {}));
  52603. //# sourceMappingURL=babylon.refractionTexture.js.map
  52604. var BABYLON;
  52605. (function (BABYLON) {
  52606. var DynamicTexture = /** @class */ (function (_super) {
  52607. __extends(DynamicTexture, _super);
  52608. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  52609. if (scene === void 0) { scene = null; }
  52610. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52611. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  52612. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  52613. _this.name = name;
  52614. _this._engine = _this.getScene().getEngine();
  52615. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52616. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52617. _this._generateMipMaps = generateMipMaps;
  52618. if (options.getContext) {
  52619. _this._canvas = options;
  52620. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52621. }
  52622. else {
  52623. _this._canvas = document.createElement("canvas");
  52624. if (options.width) {
  52625. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52626. }
  52627. else {
  52628. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  52629. }
  52630. }
  52631. var textureSize = _this.getSize();
  52632. _this._canvas.width = textureSize.width;
  52633. _this._canvas.height = textureSize.height;
  52634. _this._context = _this._canvas.getContext("2d");
  52635. return _this;
  52636. }
  52637. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  52638. get: function () {
  52639. return true;
  52640. },
  52641. enumerable: true,
  52642. configurable: true
  52643. });
  52644. DynamicTexture.prototype._recreate = function (textureSize) {
  52645. this._canvas.width = textureSize.width;
  52646. this._canvas.height = textureSize.height;
  52647. this.releaseInternalTexture();
  52648. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  52649. };
  52650. DynamicTexture.prototype.scale = function (ratio) {
  52651. var textureSize = this.getSize();
  52652. textureSize.width *= ratio;
  52653. textureSize.height *= ratio;
  52654. this._recreate(textureSize);
  52655. };
  52656. DynamicTexture.prototype.scaleTo = function (width, height) {
  52657. var textureSize = this.getSize();
  52658. textureSize.width = width;
  52659. textureSize.height = height;
  52660. this._recreate(textureSize);
  52661. };
  52662. DynamicTexture.prototype.getContext = function () {
  52663. return this._context;
  52664. };
  52665. DynamicTexture.prototype.clear = function () {
  52666. var size = this.getSize();
  52667. this._context.fillRect(0, 0, size.width, size.height);
  52668. };
  52669. DynamicTexture.prototype.update = function (invertY) {
  52670. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  52671. };
  52672. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  52673. if (update === void 0) { update = true; }
  52674. var size = this.getSize();
  52675. if (clearColor) {
  52676. this._context.fillStyle = clearColor;
  52677. this._context.fillRect(0, 0, size.width, size.height);
  52678. }
  52679. this._context.font = font;
  52680. if (x === null || x === undefined) {
  52681. var textSize = this._context.measureText(text);
  52682. x = (size.width - textSize.width) / 2;
  52683. }
  52684. if (y === null || y === undefined) {
  52685. var fontSize = parseInt((font.replace(/\D/g, '')));
  52686. ;
  52687. y = (size.height / 2) + (fontSize / 3.65);
  52688. }
  52689. this._context.fillStyle = color;
  52690. this._context.fillText(text, x, y);
  52691. if (update) {
  52692. this.update(invertY);
  52693. }
  52694. };
  52695. DynamicTexture.prototype.clone = function () {
  52696. var scene = this.getScene();
  52697. if (!scene) {
  52698. return this;
  52699. }
  52700. var textureSize = this.getSize();
  52701. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  52702. // Base texture
  52703. newTexture.hasAlpha = this.hasAlpha;
  52704. newTexture.level = this.level;
  52705. // Dynamic Texture
  52706. newTexture.wrapU = this.wrapU;
  52707. newTexture.wrapV = this.wrapV;
  52708. return newTexture;
  52709. };
  52710. DynamicTexture.prototype._rebuild = function () {
  52711. this.update();
  52712. };
  52713. return DynamicTexture;
  52714. }(BABYLON.Texture));
  52715. BABYLON.DynamicTexture = DynamicTexture;
  52716. })(BABYLON || (BABYLON = {}));
  52717. //# sourceMappingURL=babylon.dynamicTexture.js.map
  52718. var BABYLON;
  52719. (function (BABYLON) {
  52720. var VideoTexture = /** @class */ (function (_super) {
  52721. __extends(VideoTexture, _super);
  52722. /**
  52723. * Creates a video texture.
  52724. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  52725. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  52726. * @param {BABYLON.Scene} scene is obviously the current scene.
  52727. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  52728. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  52729. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  52730. */
  52731. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  52732. if (generateMipMaps === void 0) { generateMipMaps = false; }
  52733. if (invertY === void 0) { invertY = false; }
  52734. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52735. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  52736. _this._autoLaunch = true;
  52737. var urls = null;
  52738. _this.name = name;
  52739. if (urlsOrVideo instanceof HTMLVideoElement) {
  52740. _this.video = urlsOrVideo;
  52741. }
  52742. else {
  52743. urls = urlsOrVideo;
  52744. _this.video = document.createElement("video");
  52745. _this.video.autoplay = false;
  52746. _this.video.loop = true;
  52747. BABYLON.Tools.SetCorsBehavior(urls, _this.video);
  52748. }
  52749. _this._engine = _this.getScene().getEngine();
  52750. _this._generateMipMaps = generateMipMaps;
  52751. _this._samplingMode = samplingMode;
  52752. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  52753. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52754. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52755. }
  52756. else {
  52757. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52758. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52759. _this._generateMipMaps = false;
  52760. }
  52761. if (urls) {
  52762. _this.video.addEventListener("canplay", function () {
  52763. if (_this._texture === undefined) {
  52764. _this._createTexture();
  52765. }
  52766. });
  52767. urls.forEach(function (url) {
  52768. var source = document.createElement("source");
  52769. source.src = url;
  52770. _this.video.appendChild(source);
  52771. });
  52772. }
  52773. else {
  52774. _this._createTexture();
  52775. }
  52776. _this._lastUpdate = BABYLON.Tools.Now;
  52777. return _this;
  52778. }
  52779. VideoTexture.prototype.__setTextureReady = function () {
  52780. if (this._texture) {
  52781. this._texture.isReady = true;
  52782. }
  52783. };
  52784. VideoTexture.prototype._createTexture = function () {
  52785. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  52786. if (this._autoLaunch) {
  52787. this._autoLaunch = false;
  52788. this.video.play();
  52789. }
  52790. this._setTextureReady = this.__setTextureReady.bind(this);
  52791. this.video.addEventListener("playing", this._setTextureReady);
  52792. };
  52793. VideoTexture.prototype._rebuild = function () {
  52794. this.update();
  52795. };
  52796. VideoTexture.prototype.update = function () {
  52797. var now = BABYLON.Tools.Now;
  52798. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  52799. return false;
  52800. }
  52801. this._lastUpdate = now;
  52802. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  52803. return true;
  52804. };
  52805. VideoTexture.prototype.dispose = function () {
  52806. _super.prototype.dispose.call(this);
  52807. this.video.removeEventListener("playing", this._setTextureReady);
  52808. };
  52809. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  52810. var video = document.createElement("video");
  52811. var constraintsDeviceId;
  52812. if (constraints && constraints.deviceId) {
  52813. constraintsDeviceId = {
  52814. exact: constraints.deviceId
  52815. };
  52816. }
  52817. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  52818. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  52819. if (navigator.getUserMedia) {
  52820. navigator.getUserMedia({
  52821. video: {
  52822. deviceId: constraintsDeviceId,
  52823. width: {
  52824. min: (constraints && constraints.minWidth) || 256,
  52825. max: (constraints && constraints.maxWidth) || 640
  52826. },
  52827. height: {
  52828. min: (constraints && constraints.minHeight) || 256,
  52829. max: (constraints && constraints.maxHeight) || 480
  52830. }
  52831. }
  52832. }, function (stream) {
  52833. if (video.mozSrcObject !== undefined) {
  52834. video.mozSrcObject = stream;
  52835. }
  52836. else {
  52837. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  52838. }
  52839. video.play();
  52840. if (onReady) {
  52841. onReady(new VideoTexture("video", video, scene, true, true));
  52842. }
  52843. }, function (e) {
  52844. BABYLON.Tools.Error(e.name);
  52845. });
  52846. }
  52847. };
  52848. return VideoTexture;
  52849. }(BABYLON.Texture));
  52850. BABYLON.VideoTexture = VideoTexture;
  52851. })(BABYLON || (BABYLON = {}));
  52852. //# sourceMappingURL=babylon.videoTexture.js.map
  52853. var BABYLON;
  52854. (function (BABYLON) {
  52855. var RawTexture = /** @class */ (function (_super) {
  52856. __extends(RawTexture, _super);
  52857. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  52858. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52859. if (invertY === void 0) { invertY = false; }
  52860. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52861. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52862. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  52863. _this.format = format;
  52864. _this._engine = scene.getEngine();
  52865. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  52866. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52867. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52868. return _this;
  52869. }
  52870. RawTexture.prototype.update = function (data) {
  52871. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  52872. };
  52873. // Statics
  52874. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52875. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52876. if (invertY === void 0) { invertY = false; }
  52877. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52878. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  52879. };
  52880. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52881. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52882. if (invertY === void 0) { invertY = false; }
  52883. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52884. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52885. };
  52886. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52887. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52888. if (invertY === void 0) { invertY = false; }
  52889. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52890. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52891. };
  52892. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  52893. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52894. if (invertY === void 0) { invertY = false; }
  52895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52896. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52897. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  52898. };
  52899. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  52900. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52901. if (invertY === void 0) { invertY = false; }
  52902. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52903. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52904. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  52905. };
  52906. return RawTexture;
  52907. }(BABYLON.Texture));
  52908. BABYLON.RawTexture = RawTexture;
  52909. })(BABYLON || (BABYLON = {}));
  52910. //# sourceMappingURL=babylon.rawTexture.js.map
  52911. var BABYLON;
  52912. (function (BABYLON) {
  52913. var PostProcess = /** @class */ (function () {
  52914. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  52915. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  52916. if (defines === void 0) { defines = null; }
  52917. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52918. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  52919. if (blockCompilation === void 0) { blockCompilation = false; }
  52920. this.name = name;
  52921. this.width = -1;
  52922. this.height = -1;
  52923. this.autoClear = true;
  52924. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  52925. this.animations = new Array();
  52926. /*
  52927. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  52928. Can only be used on a single postprocess or on the last one of a chain.
  52929. */
  52930. this.enablePixelPerfectMode = false;
  52931. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  52932. this.alwaysForcePOT = false;
  52933. this.samples = 1;
  52934. this.adaptScaleToCurrentViewport = false;
  52935. this._reusable = false;
  52936. this._textures = new BABYLON.SmartArray(2);
  52937. this._currentRenderTextureInd = 0;
  52938. this._scaleRatio = new BABYLON.Vector2(1, 1);
  52939. this._texelSize = BABYLON.Vector2.Zero();
  52940. // Events
  52941. /**
  52942. * An event triggered when the postprocess is activated.
  52943. * @type {BABYLON.Observable}
  52944. */
  52945. this.onActivateObservable = new BABYLON.Observable();
  52946. /**
  52947. * An event triggered when the postprocess changes its size.
  52948. * @type {BABYLON.Observable}
  52949. */
  52950. this.onSizeChangedObservable = new BABYLON.Observable();
  52951. /**
  52952. * An event triggered when the postprocess applies its effect.
  52953. * @type {BABYLON.Observable}
  52954. */
  52955. this.onApplyObservable = new BABYLON.Observable();
  52956. /**
  52957. * An event triggered before rendering the postprocess
  52958. * @type {BABYLON.Observable}
  52959. */
  52960. this.onBeforeRenderObservable = new BABYLON.Observable();
  52961. /**
  52962. * An event triggered after rendering the postprocess
  52963. * @type {BABYLON.Observable}
  52964. */
  52965. this.onAfterRenderObservable = new BABYLON.Observable();
  52966. if (camera != null) {
  52967. this._camera = camera;
  52968. this._scene = camera.getScene();
  52969. camera.attachPostProcess(this);
  52970. this._engine = this._scene.getEngine();
  52971. this._scene.postProcesses.push(this);
  52972. }
  52973. else if (engine) {
  52974. this._engine = engine;
  52975. this._engine.postProcesses.push(this);
  52976. }
  52977. this._options = options;
  52978. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  52979. this._reusable = reusable || false;
  52980. this._textureType = textureType;
  52981. this._samplers = samplers || [];
  52982. this._samplers.push("textureSampler");
  52983. this._fragmentUrl = fragmentUrl;
  52984. this._vertexUrl = vertexUrl;
  52985. this._parameters = parameters || [];
  52986. this._parameters.push("scale");
  52987. this._indexParameters = indexParameters;
  52988. if (!blockCompilation) {
  52989. this.updateEffect(defines);
  52990. }
  52991. }
  52992. Object.defineProperty(PostProcess.prototype, "onActivate", {
  52993. set: function (callback) {
  52994. if (this._onActivateObserver) {
  52995. this.onActivateObservable.remove(this._onActivateObserver);
  52996. }
  52997. if (callback) {
  52998. this._onActivateObserver = this.onActivateObservable.add(callback);
  52999. }
  53000. },
  53001. enumerable: true,
  53002. configurable: true
  53003. });
  53004. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  53005. set: function (callback) {
  53006. if (this._onSizeChangedObserver) {
  53007. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  53008. }
  53009. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  53010. },
  53011. enumerable: true,
  53012. configurable: true
  53013. });
  53014. Object.defineProperty(PostProcess.prototype, "onApply", {
  53015. set: function (callback) {
  53016. if (this._onApplyObserver) {
  53017. this.onApplyObservable.remove(this._onApplyObserver);
  53018. }
  53019. this._onApplyObserver = this.onApplyObservable.add(callback);
  53020. },
  53021. enumerable: true,
  53022. configurable: true
  53023. });
  53024. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  53025. set: function (callback) {
  53026. if (this._onBeforeRenderObserver) {
  53027. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  53028. }
  53029. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  53030. },
  53031. enumerable: true,
  53032. configurable: true
  53033. });
  53034. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  53035. set: function (callback) {
  53036. if (this._onAfterRenderObserver) {
  53037. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  53038. }
  53039. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  53040. },
  53041. enumerable: true,
  53042. configurable: true
  53043. });
  53044. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  53045. get: function () {
  53046. return this._textures.data[this._currentRenderTextureInd];
  53047. },
  53048. set: function (value) {
  53049. this._forcedOutputTexture = value;
  53050. },
  53051. enumerable: true,
  53052. configurable: true
  53053. });
  53054. PostProcess.prototype.getCamera = function () {
  53055. return this._camera;
  53056. };
  53057. Object.defineProperty(PostProcess.prototype, "texelSize", {
  53058. get: function () {
  53059. if (this._shareOutputWithPostProcess) {
  53060. return this._shareOutputWithPostProcess.texelSize;
  53061. }
  53062. if (this._forcedOutputTexture) {
  53063. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  53064. }
  53065. return this._texelSize;
  53066. },
  53067. enumerable: true,
  53068. configurable: true
  53069. });
  53070. PostProcess.prototype.getEngine = function () {
  53071. return this._engine;
  53072. };
  53073. PostProcess.prototype.getEffect = function () {
  53074. return this._effect;
  53075. };
  53076. PostProcess.prototype.shareOutputWith = function (postProcess) {
  53077. this._disposeTextures();
  53078. this._shareOutputWithPostProcess = postProcess;
  53079. return this;
  53080. };
  53081. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  53082. if (defines === void 0) { defines = null; }
  53083. if (uniforms === void 0) { uniforms = null; }
  53084. if (samplers === void 0) { samplers = null; }
  53085. 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);
  53086. };
  53087. PostProcess.prototype.isReusable = function () {
  53088. return this._reusable;
  53089. };
  53090. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  53091. PostProcess.prototype.markTextureDirty = function () {
  53092. this.width = -1;
  53093. };
  53094. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  53095. var _this = this;
  53096. if (sourceTexture === void 0) { sourceTexture = null; }
  53097. camera = camera || this._camera;
  53098. var scene = camera.getScene();
  53099. var engine = scene.getEngine();
  53100. var maxSize = engine.getCaps().maxTextureSize;
  53101. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  53102. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  53103. var desiredWidth = (this._options.width || requiredWidth);
  53104. var desiredHeight = this._options.height || requiredHeight;
  53105. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  53106. if (this.adaptScaleToCurrentViewport) {
  53107. var currentViewport = engine.currentViewport;
  53108. if (currentViewport) {
  53109. desiredWidth *= currentViewport.width;
  53110. desiredHeight *= currentViewport.height;
  53111. }
  53112. }
  53113. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  53114. if (!this._options.width) {
  53115. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  53116. }
  53117. if (!this._options.height) {
  53118. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  53119. }
  53120. }
  53121. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  53122. if (this._textures.length > 0) {
  53123. for (var i = 0; i < this._textures.length; i++) {
  53124. this._engine._releaseTexture(this._textures.data[i]);
  53125. }
  53126. this._textures.reset();
  53127. }
  53128. this.width = desiredWidth;
  53129. this.height = desiredHeight;
  53130. var textureSize = { width: this.width, height: this.height };
  53131. var textureOptions = {
  53132. generateMipMaps: false,
  53133. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  53134. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  53135. samplingMode: this.renderTargetSamplingMode,
  53136. type: this._textureType
  53137. };
  53138. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  53139. if (this._reusable) {
  53140. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  53141. }
  53142. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  53143. this.onSizeChangedObservable.notifyObservers(this);
  53144. }
  53145. this._textures.forEach(function (texture) {
  53146. if (texture.samples !== _this.samples) {
  53147. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  53148. }
  53149. });
  53150. }
  53151. var target;
  53152. if (this._shareOutputWithPostProcess) {
  53153. target = this._shareOutputWithPostProcess.outputTexture;
  53154. }
  53155. else if (this._forcedOutputTexture) {
  53156. target = this._forcedOutputTexture;
  53157. this.width = this._forcedOutputTexture.width;
  53158. this.height = this._forcedOutputTexture.height;
  53159. }
  53160. else {
  53161. target = this.outputTexture;
  53162. }
  53163. if (this.enablePixelPerfectMode) {
  53164. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  53165. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  53166. }
  53167. else {
  53168. this._scaleRatio.copyFromFloats(1, 1);
  53169. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  53170. }
  53171. this.onActivateObservable.notifyObservers(camera);
  53172. // Clear
  53173. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  53174. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  53175. }
  53176. if (this._reusable) {
  53177. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  53178. }
  53179. };
  53180. Object.defineProperty(PostProcess.prototype, "isSupported", {
  53181. get: function () {
  53182. return this._effect.isSupported;
  53183. },
  53184. enumerable: true,
  53185. configurable: true
  53186. });
  53187. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  53188. get: function () {
  53189. if (this._shareOutputWithPostProcess) {
  53190. return this._shareOutputWithPostProcess.aspectRatio;
  53191. }
  53192. if (this._forcedOutputTexture) {
  53193. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  53194. }
  53195. return this.width / this.height;
  53196. },
  53197. enumerable: true,
  53198. configurable: true
  53199. });
  53200. /**
  53201. * Get a value indicating if the post-process is ready to be used
  53202. * @returns true if the post-process is ready (shader is compiled)
  53203. */
  53204. PostProcess.prototype.isReady = function () {
  53205. return this._effect && this._effect.isReady();
  53206. };
  53207. PostProcess.prototype.apply = function () {
  53208. // Check
  53209. if (!this._effect || !this._effect.isReady())
  53210. return null;
  53211. // States
  53212. this._engine.enableEffect(this._effect);
  53213. this._engine.setState(false);
  53214. this._engine.setDepthBuffer(false);
  53215. this._engine.setDepthWrite(false);
  53216. // Alpha
  53217. this._engine.setAlphaMode(this.alphaMode);
  53218. if (this.alphaConstants) {
  53219. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  53220. }
  53221. // Texture
  53222. var source;
  53223. if (this._shareOutputWithPostProcess) {
  53224. source = this._shareOutputWithPostProcess.outputTexture;
  53225. }
  53226. else if (this._forcedOutputTexture) {
  53227. source = this._forcedOutputTexture;
  53228. }
  53229. else {
  53230. source = this.outputTexture;
  53231. }
  53232. this._effect._bindTexture("textureSampler", source);
  53233. // Parameters
  53234. this._effect.setVector2("scale", this._scaleRatio);
  53235. this.onApplyObservable.notifyObservers(this._effect);
  53236. return this._effect;
  53237. };
  53238. PostProcess.prototype._disposeTextures = function () {
  53239. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  53240. return;
  53241. }
  53242. if (this._textures.length > 0) {
  53243. for (var i = 0; i < this._textures.length; i++) {
  53244. this._engine._releaseTexture(this._textures.data[i]);
  53245. }
  53246. }
  53247. this._textures.dispose();
  53248. };
  53249. PostProcess.prototype.dispose = function (camera) {
  53250. camera = camera || this._camera;
  53251. this._disposeTextures();
  53252. if (this._scene) {
  53253. var index_1 = this._scene.postProcesses.indexOf(this);
  53254. if (index_1 !== -1) {
  53255. this._scene.postProcesses.splice(index_1, 1);
  53256. }
  53257. }
  53258. else {
  53259. var index_2 = this._engine.postProcesses.indexOf(this);
  53260. if (index_2 !== -1) {
  53261. this._engine.postProcesses.splice(index_2, 1);
  53262. }
  53263. }
  53264. if (!camera) {
  53265. return;
  53266. }
  53267. camera.detachPostProcess(this);
  53268. var index = camera._postProcesses.indexOf(this);
  53269. if (index === 0 && camera._postProcesses.length > 0) {
  53270. this._camera._postProcesses[0].markTextureDirty();
  53271. }
  53272. this.onActivateObservable.clear();
  53273. this.onAfterRenderObservable.clear();
  53274. this.onApplyObservable.clear();
  53275. this.onBeforeRenderObservable.clear();
  53276. this.onSizeChangedObservable.clear();
  53277. };
  53278. return PostProcess;
  53279. }());
  53280. BABYLON.PostProcess = PostProcess;
  53281. })(BABYLON || (BABYLON = {}));
  53282. //# sourceMappingURL=babylon.postProcess.js.map
  53283. var BABYLON;
  53284. (function (BABYLON) {
  53285. var PassPostProcess = /** @class */ (function (_super) {
  53286. __extends(PassPostProcess, _super);
  53287. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53288. if (camera === void 0) { camera = null; }
  53289. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53290. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  53291. }
  53292. return PassPostProcess;
  53293. }(BABYLON.PostProcess));
  53294. BABYLON.PassPostProcess = PassPostProcess;
  53295. })(BABYLON || (BABYLON = {}));
  53296. //# sourceMappingURL=babylon.passPostProcess.js.map
  53297. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53298. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53299. s = arguments[i];
  53300. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53301. t[p] = s[p];
  53302. }
  53303. return t;
  53304. };
  53305. var BABYLON;
  53306. (function (BABYLON) {
  53307. var ShadowGenerator = /** @class */ (function () {
  53308. /**
  53309. * Creates a ShadowGenerator object.
  53310. * A ShadowGenerator is the required tool to use the shadows.
  53311. * Each light casting shadows needs to use its own ShadowGenerator.
  53312. * Required parameters :
  53313. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  53314. * - `light`: the light object generating the shadows.
  53315. * - `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.
  53316. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  53317. */
  53318. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  53319. // Members
  53320. this._bias = 0.00005;
  53321. this._blurBoxOffset = 1;
  53322. this._blurScale = 2;
  53323. this._blurKernel = 1;
  53324. this._useKernelBlur = false;
  53325. this._filter = ShadowGenerator.FILTER_NONE;
  53326. this._darkness = 0;
  53327. this._transparencyShadow = false;
  53328. /**
  53329. * Controls the extent to which the shadows fade out at the edge of the frustum
  53330. * Used only by directionals and spots
  53331. */
  53332. this.frustumEdgeFalloff = 0;
  53333. this.forceBackFacesOnly = false;
  53334. this._lightDirection = BABYLON.Vector3.Zero();
  53335. this._viewMatrix = BABYLON.Matrix.Zero();
  53336. this._projectionMatrix = BABYLON.Matrix.Zero();
  53337. this._transformMatrix = BABYLON.Matrix.Zero();
  53338. this._currentFaceIndex = 0;
  53339. this._currentFaceIndexCache = 0;
  53340. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  53341. this._mapSize = mapSize;
  53342. this._light = light;
  53343. this._scene = light.getScene();
  53344. light._shadowGenerator = this;
  53345. // Texture type fallback from float to int if not supported.
  53346. var caps = this._scene.getEngine().getCaps();
  53347. if (!useFullFloatFirst) {
  53348. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  53349. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53350. }
  53351. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  53352. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53353. }
  53354. else {
  53355. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53356. }
  53357. }
  53358. else {
  53359. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  53360. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53361. }
  53362. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  53363. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53364. }
  53365. else {
  53366. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53367. }
  53368. }
  53369. this._initializeGenerator();
  53370. }
  53371. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  53372. // Static
  53373. get: function () {
  53374. return ShadowGenerator._FILTER_NONE;
  53375. },
  53376. enumerable: true,
  53377. configurable: true
  53378. });
  53379. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  53380. get: function () {
  53381. return ShadowGenerator._FILTER_POISSONSAMPLING;
  53382. },
  53383. enumerable: true,
  53384. configurable: true
  53385. });
  53386. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  53387. get: function () {
  53388. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  53389. },
  53390. enumerable: true,
  53391. configurable: true
  53392. });
  53393. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  53394. get: function () {
  53395. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  53396. },
  53397. enumerable: true,
  53398. configurable: true
  53399. });
  53400. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  53401. get: function () {
  53402. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53403. },
  53404. enumerable: true,
  53405. configurable: true
  53406. });
  53407. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  53408. get: function () {
  53409. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53410. },
  53411. enumerable: true,
  53412. configurable: true
  53413. });
  53414. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  53415. get: function () {
  53416. return this._bias;
  53417. },
  53418. set: function (bias) {
  53419. this._bias = bias;
  53420. },
  53421. enumerable: true,
  53422. configurable: true
  53423. });
  53424. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  53425. get: function () {
  53426. return this._blurBoxOffset;
  53427. },
  53428. set: function (value) {
  53429. if (this._blurBoxOffset === value) {
  53430. return;
  53431. }
  53432. this._blurBoxOffset = value;
  53433. this._disposeBlurPostProcesses();
  53434. },
  53435. enumerable: true,
  53436. configurable: true
  53437. });
  53438. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  53439. get: function () {
  53440. return this._blurScale;
  53441. },
  53442. set: function (value) {
  53443. if (this._blurScale === value) {
  53444. return;
  53445. }
  53446. this._blurScale = value;
  53447. this._disposeBlurPostProcesses();
  53448. },
  53449. enumerable: true,
  53450. configurable: true
  53451. });
  53452. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  53453. get: function () {
  53454. return this._blurKernel;
  53455. },
  53456. set: function (value) {
  53457. if (this._blurKernel === value) {
  53458. return;
  53459. }
  53460. this._blurKernel = value;
  53461. this._disposeBlurPostProcesses();
  53462. },
  53463. enumerable: true,
  53464. configurable: true
  53465. });
  53466. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  53467. get: function () {
  53468. return this._useKernelBlur;
  53469. },
  53470. set: function (value) {
  53471. if (this._useKernelBlur === value) {
  53472. return;
  53473. }
  53474. this._useKernelBlur = value;
  53475. this._disposeBlurPostProcesses();
  53476. },
  53477. enumerable: true,
  53478. configurable: true
  53479. });
  53480. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  53481. get: function () {
  53482. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  53483. },
  53484. set: function (value) {
  53485. this._depthScale = value;
  53486. },
  53487. enumerable: true,
  53488. configurable: true
  53489. });
  53490. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  53491. get: function () {
  53492. return this._filter;
  53493. },
  53494. set: function (value) {
  53495. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  53496. if (this._light.needCube()) {
  53497. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53498. this.useExponentialShadowMap = true;
  53499. return;
  53500. }
  53501. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53502. this.useCloseExponentialShadowMap = true;
  53503. return;
  53504. }
  53505. }
  53506. if (this._filter === value) {
  53507. return;
  53508. }
  53509. this._filter = value;
  53510. this._disposeBlurPostProcesses();
  53511. this._applyFilterValues();
  53512. this._light._markMeshesAsLightDirty();
  53513. },
  53514. enumerable: true,
  53515. configurable: true
  53516. });
  53517. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  53518. get: function () {
  53519. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  53520. },
  53521. set: function (value) {
  53522. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  53523. return;
  53524. }
  53525. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  53526. },
  53527. enumerable: true,
  53528. configurable: true
  53529. });
  53530. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  53531. get: function () {
  53532. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53533. return this.useExponentialShadowMap;
  53534. },
  53535. set: function (value) {
  53536. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53537. this.useExponentialShadowMap = value;
  53538. },
  53539. enumerable: true,
  53540. configurable: true
  53541. });
  53542. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  53543. get: function () {
  53544. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53545. return this.useBlurExponentialShadowMap;
  53546. },
  53547. set: function (value) {
  53548. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53549. this.useBlurExponentialShadowMap = value;
  53550. },
  53551. enumerable: true,
  53552. configurable: true
  53553. });
  53554. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  53555. get: function () {
  53556. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  53557. },
  53558. set: function (value) {
  53559. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  53560. return;
  53561. }
  53562. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53563. },
  53564. enumerable: true,
  53565. configurable: true
  53566. });
  53567. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  53568. get: function () {
  53569. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  53570. },
  53571. set: function (value) {
  53572. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53573. return;
  53574. }
  53575. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53576. },
  53577. enumerable: true,
  53578. configurable: true
  53579. });
  53580. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  53581. get: function () {
  53582. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53583. },
  53584. set: function (value) {
  53585. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  53586. return;
  53587. }
  53588. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53589. },
  53590. enumerable: true,
  53591. configurable: true
  53592. });
  53593. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  53594. get: function () {
  53595. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53596. },
  53597. set: function (value) {
  53598. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53599. return;
  53600. }
  53601. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53602. },
  53603. enumerable: true,
  53604. configurable: true
  53605. });
  53606. /**
  53607. * Returns the darkness value (float).
  53608. */
  53609. ShadowGenerator.prototype.getDarkness = function () {
  53610. return this._darkness;
  53611. };
  53612. /**
  53613. * Sets the ShadowGenerator darkness value (float <= 1.0).
  53614. * Returns the ShadowGenerator.
  53615. */
  53616. ShadowGenerator.prototype.setDarkness = function (darkness) {
  53617. if (darkness >= 1.0)
  53618. this._darkness = 1.0;
  53619. else if (darkness <= 0.0)
  53620. this._darkness = 0.0;
  53621. else
  53622. this._darkness = darkness;
  53623. return this;
  53624. };
  53625. /**
  53626. * Sets the ability to have transparent shadow (boolean).
  53627. * Returns the ShadowGenerator.
  53628. */
  53629. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  53630. this._transparencyShadow = hasShadow;
  53631. return this;
  53632. };
  53633. /**
  53634. * Returns a RenderTargetTexture object : the shadow map texture.
  53635. */
  53636. ShadowGenerator.prototype.getShadowMap = function () {
  53637. return this._shadowMap;
  53638. };
  53639. /**
  53640. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  53641. */
  53642. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  53643. if (this._shadowMap2) {
  53644. return this._shadowMap2;
  53645. }
  53646. return this._shadowMap;
  53647. };
  53648. /**
  53649. * Helper function to add a mesh and its descendants to the list of shadow casters
  53650. * @param mesh Mesh to add
  53651. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  53652. */
  53653. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  53654. if (includeDescendants === void 0) { includeDescendants = true; }
  53655. if (!this._shadowMap) {
  53656. return this;
  53657. }
  53658. if (!this._shadowMap.renderList) {
  53659. this._shadowMap.renderList = [];
  53660. }
  53661. this._shadowMap.renderList.push(mesh);
  53662. if (includeDescendants) {
  53663. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  53664. }
  53665. return this;
  53666. var _a;
  53667. };
  53668. /**
  53669. * Helper function to remove a mesh and its descendants from the list of shadow casters
  53670. * @param mesh Mesh to remove
  53671. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  53672. */
  53673. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  53674. if (includeDescendants === void 0) { includeDescendants = true; }
  53675. if (!this._shadowMap || !this._shadowMap.renderList) {
  53676. return this;
  53677. }
  53678. var index = this._shadowMap.renderList.indexOf(mesh);
  53679. if (index !== -1) {
  53680. this._shadowMap.renderList.splice(index, 1);
  53681. }
  53682. if (includeDescendants) {
  53683. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  53684. var child = _a[_i];
  53685. this.removeShadowCaster(child);
  53686. }
  53687. }
  53688. return this;
  53689. };
  53690. /**
  53691. * Returns the associated light object.
  53692. */
  53693. ShadowGenerator.prototype.getLight = function () {
  53694. return this._light;
  53695. };
  53696. ShadowGenerator.prototype._initializeGenerator = function () {
  53697. this._light._markMeshesAsLightDirty();
  53698. this._initializeShadowMap();
  53699. };
  53700. ShadowGenerator.prototype._initializeShadowMap = function () {
  53701. var _this = this;
  53702. // Render target
  53703. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  53704. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53705. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53706. this._shadowMap.anisotropicFilteringLevel = 1;
  53707. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53708. this._shadowMap.renderParticles = false;
  53709. this._shadowMap.ignoreCameraViewport = true;
  53710. // Record Face Index before render.
  53711. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  53712. _this._currentFaceIndex = faceIndex;
  53713. });
  53714. // Custom render function.
  53715. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  53716. // Blur if required afer render.
  53717. this._shadowMap.onAfterUnbindObservable.add(function () {
  53718. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  53719. return;
  53720. }
  53721. var shadowMap = _this.getShadowMapForRendering();
  53722. if (shadowMap) {
  53723. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  53724. }
  53725. });
  53726. // Clear according to the chosen filter.
  53727. this._shadowMap.onClearObservable.add(function (engine) {
  53728. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  53729. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  53730. }
  53731. else {
  53732. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  53733. }
  53734. });
  53735. };
  53736. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  53737. var _this = this;
  53738. var engine = this._scene.getEngine();
  53739. var targetSize = this._mapSize / this.blurScale;
  53740. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  53741. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  53742. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53743. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53744. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53745. }
  53746. if (this.useKernelBlur) {
  53747. 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);
  53748. this._kernelBlurXPostprocess.width = targetSize;
  53749. this._kernelBlurXPostprocess.height = targetSize;
  53750. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  53751. effect.setTexture("textureSampler", _this._shadowMap);
  53752. });
  53753. 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);
  53754. this._kernelBlurXPostprocess.autoClear = false;
  53755. this._kernelBlurYPostprocess.autoClear = false;
  53756. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53757. this._kernelBlurXPostprocess.packedFloat = true;
  53758. this._kernelBlurYPostprocess.packedFloat = true;
  53759. }
  53760. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  53761. }
  53762. else {
  53763. 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);
  53764. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  53765. effect.setFloat2("screenSize", targetSize, targetSize);
  53766. effect.setTexture("textureSampler", _this._shadowMap);
  53767. });
  53768. this._boxBlurPostprocess.autoClear = false;
  53769. this._blurPostProcesses = [this._boxBlurPostprocess];
  53770. }
  53771. };
  53772. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  53773. var index;
  53774. var engine = this._scene.getEngine();
  53775. if (depthOnlySubMeshes.length) {
  53776. engine.setColorWrite(false);
  53777. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  53778. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  53779. }
  53780. engine.setColorWrite(true);
  53781. }
  53782. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53783. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  53784. }
  53785. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53786. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  53787. }
  53788. if (this._transparencyShadow) {
  53789. for (index = 0; index < transparentSubMeshes.length; index++) {
  53790. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  53791. }
  53792. }
  53793. };
  53794. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  53795. var _this = this;
  53796. var mesh = subMesh.getRenderingMesh();
  53797. var scene = this._scene;
  53798. var engine = scene.getEngine();
  53799. var material = subMesh.getMaterial();
  53800. if (!material) {
  53801. return;
  53802. }
  53803. // Culling
  53804. engine.setState(material.backFaceCulling);
  53805. // Managing instances
  53806. var batch = mesh._getInstancesRenderList(subMesh._id);
  53807. if (batch.mustReturn) {
  53808. return;
  53809. }
  53810. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  53811. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  53812. engine.enableEffect(this._effect);
  53813. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  53814. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  53815. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  53816. this._effect.setVector3("lightPosition", this.getLight().position);
  53817. if (scene.activeCamera) {
  53818. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  53819. }
  53820. // Alpha test
  53821. if (material && material.needAlphaTesting()) {
  53822. var alphaTexture = material.getAlphaTestTexture();
  53823. if (alphaTexture) {
  53824. this._effect.setTexture("diffuseSampler", alphaTexture);
  53825. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  53826. }
  53827. }
  53828. // Bones
  53829. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53830. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  53831. }
  53832. if (this.forceBackFacesOnly) {
  53833. engine.setState(true, 0, false, true);
  53834. }
  53835. // Draw
  53836. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53837. if (this.forceBackFacesOnly) {
  53838. engine.setState(true, 0, false, false);
  53839. }
  53840. }
  53841. else {
  53842. // Need to reset refresh rate of the shadowMap
  53843. if (this._shadowMap) {
  53844. this._shadowMap.resetRefreshCounter();
  53845. }
  53846. }
  53847. };
  53848. ShadowGenerator.prototype._applyFilterValues = function () {
  53849. if (!this._shadowMap) {
  53850. return;
  53851. }
  53852. if (this.filter === ShadowGenerator.FILTER_NONE) {
  53853. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  53854. }
  53855. else {
  53856. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53857. }
  53858. };
  53859. /**
  53860. * Force shader compilation including textures ready check
  53861. */
  53862. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  53863. var _this = this;
  53864. var localOptions = __assign({ useInstances: false }, options);
  53865. var shadowMap = this.getShadowMap();
  53866. if (!shadowMap) {
  53867. if (onCompiled) {
  53868. onCompiled(this);
  53869. }
  53870. return;
  53871. }
  53872. var renderList = shadowMap.renderList;
  53873. if (!renderList) {
  53874. if (onCompiled) {
  53875. onCompiled(this);
  53876. }
  53877. return;
  53878. }
  53879. var subMeshes = new Array();
  53880. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  53881. var mesh = renderList_1[_i];
  53882. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  53883. }
  53884. if (subMeshes.length === 0) {
  53885. if (onCompiled) {
  53886. onCompiled(this);
  53887. }
  53888. return;
  53889. }
  53890. var currentIndex = 0;
  53891. var checkReady = function () {
  53892. if (!_this._scene || !_this._scene.getEngine()) {
  53893. return;
  53894. }
  53895. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  53896. currentIndex++;
  53897. if (currentIndex >= subMeshes.length) {
  53898. if (onCompiled) {
  53899. onCompiled(_this);
  53900. }
  53901. return;
  53902. }
  53903. }
  53904. setTimeout(checkReady, 16);
  53905. };
  53906. checkReady();
  53907. };
  53908. /**
  53909. * Boolean : true when the ShadowGenerator is finally computed.
  53910. */
  53911. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  53912. var defines = [];
  53913. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53914. defines.push("#define FLOAT");
  53915. }
  53916. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  53917. defines.push("#define ESM");
  53918. }
  53919. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53920. var mesh = subMesh.getMesh();
  53921. var material = subMesh.getMaterial();
  53922. // Alpha test
  53923. if (material && material.needAlphaTesting()) {
  53924. var alphaTexture = material.getAlphaTestTexture();
  53925. if (alphaTexture) {
  53926. defines.push("#define ALPHATEST");
  53927. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53928. attribs.push(BABYLON.VertexBuffer.UVKind);
  53929. defines.push("#define UV1");
  53930. }
  53931. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53932. if (alphaTexture.coordinatesIndex === 1) {
  53933. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53934. defines.push("#define UV2");
  53935. }
  53936. }
  53937. }
  53938. }
  53939. // Bones
  53940. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53941. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53942. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53943. if (mesh.numBoneInfluencers > 4) {
  53944. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53945. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53946. }
  53947. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53948. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53949. }
  53950. else {
  53951. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53952. }
  53953. // Instances
  53954. if (useInstances) {
  53955. defines.push("#define INSTANCES");
  53956. attribs.push("world0");
  53957. attribs.push("world1");
  53958. attribs.push("world2");
  53959. attribs.push("world3");
  53960. }
  53961. // Get correct effect
  53962. var join = defines.join("\n");
  53963. if (this._cachedDefines !== join) {
  53964. this._cachedDefines = join;
  53965. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  53966. }
  53967. if (!this._effect.isReady()) {
  53968. return false;
  53969. }
  53970. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  53971. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  53972. this._initializeBlurRTTAndPostProcesses();
  53973. }
  53974. }
  53975. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  53976. return false;
  53977. }
  53978. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  53979. return false;
  53980. }
  53981. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  53982. return false;
  53983. }
  53984. return true;
  53985. };
  53986. /**
  53987. * This creates the defines related to the standard BJS materials.
  53988. */
  53989. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  53990. var scene = this._scene;
  53991. var light = this._light;
  53992. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  53993. return;
  53994. }
  53995. defines["SHADOW" + lightIndex] = true;
  53996. if (this.usePoissonSampling) {
  53997. defines["SHADOWPCF" + lightIndex] = true;
  53998. }
  53999. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  54000. defines["SHADOWESM" + lightIndex] = true;
  54001. }
  54002. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  54003. defines["SHADOWCLOSEESM" + lightIndex] = true;
  54004. }
  54005. if (light.needCube()) {
  54006. defines["SHADOWCUBE" + lightIndex] = true;
  54007. }
  54008. };
  54009. /**
  54010. * This binds shadow lights related to the standard BJS materials.
  54011. * It implies the unifroms available on the materials are the standard BJS ones.
  54012. */
  54013. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  54014. var light = this._light;
  54015. var scene = this._scene;
  54016. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  54017. return;
  54018. }
  54019. var camera = scene.activeCamera;
  54020. if (!camera) {
  54021. return;
  54022. }
  54023. var shadowMap = this.getShadowMap();
  54024. if (!shadowMap) {
  54025. return;
  54026. }
  54027. if (!light.needCube()) {
  54028. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  54029. }
  54030. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  54031. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  54032. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  54033. };
  54034. // Methods
  54035. /**
  54036. * Returns a Matrix object : the updated transformation matrix.
  54037. */
  54038. ShadowGenerator.prototype.getTransformMatrix = function () {
  54039. var scene = this._scene;
  54040. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  54041. return this._transformMatrix;
  54042. }
  54043. this._currentRenderID = scene.getRenderId();
  54044. this._currentFaceIndexCache = this._currentFaceIndex;
  54045. var lightPosition = this._light.position;
  54046. if (this._light.computeTransformedInformation()) {
  54047. lightPosition = this._light.transformedPosition;
  54048. }
  54049. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  54050. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  54051. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  54052. }
  54053. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  54054. this._cachedPosition = lightPosition.clone();
  54055. this._cachedDirection = this._lightDirection.clone();
  54056. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  54057. var shadowMap = this.getShadowMap();
  54058. if (shadowMap) {
  54059. var renderList = shadowMap.renderList;
  54060. if (renderList) {
  54061. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  54062. }
  54063. }
  54064. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  54065. }
  54066. return this._transformMatrix;
  54067. };
  54068. ShadowGenerator.prototype.recreateShadowMap = function () {
  54069. var shadowMap = this._shadowMap;
  54070. if (!shadowMap) {
  54071. return;
  54072. }
  54073. // Track render list.
  54074. var renderList = shadowMap.renderList;
  54075. // Clean up existing data.
  54076. this._disposeRTTandPostProcesses();
  54077. // Reinitializes.
  54078. this._initializeGenerator();
  54079. // Reaffect the filter to ensure a correct fallback if necessary.
  54080. this.filter = this.filter;
  54081. // Reaffect the filter.
  54082. this._applyFilterValues();
  54083. // Reaffect Render List.
  54084. this._shadowMap.renderList = renderList;
  54085. };
  54086. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  54087. if (this._shadowMap2) {
  54088. this._shadowMap2.dispose();
  54089. this._shadowMap2 = null;
  54090. }
  54091. if (this._boxBlurPostprocess) {
  54092. this._boxBlurPostprocess.dispose();
  54093. this._boxBlurPostprocess = null;
  54094. }
  54095. if (this._kernelBlurXPostprocess) {
  54096. this._kernelBlurXPostprocess.dispose();
  54097. this._kernelBlurXPostprocess = null;
  54098. }
  54099. if (this._kernelBlurYPostprocess) {
  54100. this._kernelBlurYPostprocess.dispose();
  54101. this._kernelBlurYPostprocess = null;
  54102. }
  54103. this._blurPostProcesses = [];
  54104. };
  54105. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  54106. if (this._shadowMap) {
  54107. this._shadowMap.dispose();
  54108. this._shadowMap = null;
  54109. }
  54110. this._disposeBlurPostProcesses();
  54111. };
  54112. /**
  54113. * Disposes the ShadowGenerator.
  54114. * Returns nothing.
  54115. */
  54116. ShadowGenerator.prototype.dispose = function () {
  54117. this._disposeRTTandPostProcesses();
  54118. if (this._light) {
  54119. this._light._shadowGenerator = null;
  54120. this._light._markMeshesAsLightDirty();
  54121. }
  54122. };
  54123. /**
  54124. * Serializes the ShadowGenerator and returns a serializationObject.
  54125. */
  54126. ShadowGenerator.prototype.serialize = function () {
  54127. var serializationObject = {};
  54128. var shadowMap = this.getShadowMap();
  54129. if (!shadowMap) {
  54130. return serializationObject;
  54131. }
  54132. serializationObject.lightId = this._light.id;
  54133. serializationObject.mapSize = shadowMap.getRenderSize();
  54134. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  54135. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  54136. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  54137. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  54138. serializationObject.usePoissonSampling = this.usePoissonSampling;
  54139. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  54140. serializationObject.depthScale = this.depthScale;
  54141. serializationObject.darkness = this.getDarkness();
  54142. serializationObject.blurBoxOffset = this.blurBoxOffset;
  54143. serializationObject.blurKernel = this.blurKernel;
  54144. serializationObject.blurScale = this.blurScale;
  54145. serializationObject.useKernelBlur = this.useKernelBlur;
  54146. serializationObject.transparencyShadow = this._transparencyShadow;
  54147. serializationObject.renderList = [];
  54148. if (shadowMap.renderList) {
  54149. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  54150. var mesh = shadowMap.renderList[meshIndex];
  54151. serializationObject.renderList.push(mesh.id);
  54152. }
  54153. }
  54154. return serializationObject;
  54155. };
  54156. /**
  54157. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  54158. */
  54159. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  54160. //casting to point light, as light is missing the position attr and typescript complains.
  54161. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  54162. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  54163. var shadowMap = shadowGenerator.getShadowMap();
  54164. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  54165. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  54166. meshes.forEach(function (mesh) {
  54167. if (!shadowMap) {
  54168. return;
  54169. }
  54170. if (!shadowMap.renderList) {
  54171. shadowMap.renderList = [];
  54172. }
  54173. shadowMap.renderList.push(mesh);
  54174. });
  54175. }
  54176. if (parsedShadowGenerator.usePoissonSampling) {
  54177. shadowGenerator.usePoissonSampling = true;
  54178. }
  54179. else if (parsedShadowGenerator.useExponentialShadowMap) {
  54180. shadowGenerator.useExponentialShadowMap = true;
  54181. }
  54182. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  54183. shadowGenerator.useBlurExponentialShadowMap = true;
  54184. }
  54185. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  54186. shadowGenerator.useCloseExponentialShadowMap = true;
  54187. }
  54188. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  54189. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  54190. }
  54191. else if (parsedShadowGenerator.useVarianceShadowMap) {
  54192. shadowGenerator.useExponentialShadowMap = true;
  54193. }
  54194. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  54195. shadowGenerator.useBlurExponentialShadowMap = true;
  54196. }
  54197. if (parsedShadowGenerator.depthScale) {
  54198. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  54199. }
  54200. if (parsedShadowGenerator.blurScale) {
  54201. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  54202. }
  54203. if (parsedShadowGenerator.blurBoxOffset) {
  54204. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  54205. }
  54206. if (parsedShadowGenerator.useKernelBlur) {
  54207. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  54208. }
  54209. if (parsedShadowGenerator.blurKernel) {
  54210. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  54211. }
  54212. if (parsedShadowGenerator.bias !== undefined) {
  54213. shadowGenerator.bias = parsedShadowGenerator.bias;
  54214. }
  54215. if (parsedShadowGenerator.darkness) {
  54216. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  54217. }
  54218. if (parsedShadowGenerator.transparencyShadow) {
  54219. shadowGenerator.setTransparencyShadow(true);
  54220. }
  54221. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  54222. return shadowGenerator;
  54223. };
  54224. ShadowGenerator._FILTER_NONE = 0;
  54225. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  54226. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  54227. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  54228. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  54229. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  54230. return ShadowGenerator;
  54231. }());
  54232. BABYLON.ShadowGenerator = ShadowGenerator;
  54233. })(BABYLON || (BABYLON = {}));
  54234. //# sourceMappingURL=babylon.shadowGenerator.js.map
  54235. var BABYLON;
  54236. (function (BABYLON) {
  54237. var DefaultLoadingScreen = /** @class */ (function () {
  54238. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  54239. if (_loadingText === void 0) { _loadingText = ""; }
  54240. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  54241. var _this = this;
  54242. this._renderingCanvas = _renderingCanvas;
  54243. this._loadingText = _loadingText;
  54244. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  54245. // Resize
  54246. this._resizeLoadingUI = function () {
  54247. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  54248. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  54249. if (!_this._loadingDiv) {
  54250. return;
  54251. }
  54252. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  54253. _this._loadingDiv.style.left = canvasRect.left + "px";
  54254. _this._loadingDiv.style.top = canvasRect.top + "px";
  54255. _this._loadingDiv.style.width = canvasRect.width + "px";
  54256. _this._loadingDiv.style.height = canvasRect.height + "px";
  54257. };
  54258. }
  54259. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  54260. if (this._loadingDiv) {
  54261. // Do not add a loading screen if there is already one
  54262. return;
  54263. }
  54264. this._loadingDiv = document.createElement("div");
  54265. this._loadingDiv.id = "babylonjsLoadingDiv";
  54266. this._loadingDiv.style.opacity = "0";
  54267. this._loadingDiv.style.transition = "opacity 1.5s ease";
  54268. this._loadingDiv.style.pointerEvents = "none";
  54269. // Loading text
  54270. this._loadingTextDiv = document.createElement("div");
  54271. this._loadingTextDiv.style.position = "absolute";
  54272. this._loadingTextDiv.style.left = "0";
  54273. this._loadingTextDiv.style.top = "50%";
  54274. this._loadingTextDiv.style.marginTop = "80px";
  54275. this._loadingTextDiv.style.width = "100%";
  54276. this._loadingTextDiv.style.height = "20px";
  54277. this._loadingTextDiv.style.fontFamily = "Arial";
  54278. this._loadingTextDiv.style.fontSize = "14px";
  54279. this._loadingTextDiv.style.color = "white";
  54280. this._loadingTextDiv.style.textAlign = "center";
  54281. this._loadingTextDiv.innerHTML = "Loading";
  54282. this._loadingDiv.appendChild(this._loadingTextDiv);
  54283. //set the predefined text
  54284. this._loadingTextDiv.innerHTML = this._loadingText;
  54285. // Generating keyframes
  54286. var style = document.createElement('style');
  54287. style.type = 'text/css';
  54288. 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 }";
  54289. style.innerHTML = keyFrames;
  54290. document.getElementsByTagName('head')[0].appendChild(style);
  54291. // Loading img
  54292. var imgBack = new Image();
  54293. 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";
  54294. imgBack.style.position = "absolute";
  54295. imgBack.style.left = "50%";
  54296. imgBack.style.top = "50%";
  54297. imgBack.style.marginLeft = "-60px";
  54298. imgBack.style.marginTop = "-60px";
  54299. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  54300. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  54301. imgBack.style.transformOrigin = "50% 50%";
  54302. imgBack.style.webkitTransformOrigin = "50% 50%";
  54303. this._loadingDiv.appendChild(imgBack);
  54304. this._resizeLoadingUI();
  54305. window.addEventListener("resize", this._resizeLoadingUI);
  54306. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  54307. document.body.appendChild(this._loadingDiv);
  54308. this._loadingDiv.style.opacity = "1";
  54309. };
  54310. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  54311. var _this = this;
  54312. if (!this._loadingDiv) {
  54313. return;
  54314. }
  54315. var onTransitionEnd = function () {
  54316. if (!_this._loadingDiv) {
  54317. return;
  54318. }
  54319. document.body.removeChild(_this._loadingDiv);
  54320. window.removeEventListener("resize", _this._resizeLoadingUI);
  54321. _this._loadingDiv = null;
  54322. };
  54323. this._loadingDiv.style.opacity = "0";
  54324. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  54325. };
  54326. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  54327. set: function (text) {
  54328. this._loadingText = text;
  54329. if (this._loadingTextDiv) {
  54330. this._loadingTextDiv.innerHTML = this._loadingText;
  54331. }
  54332. },
  54333. enumerable: true,
  54334. configurable: true
  54335. });
  54336. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  54337. get: function () {
  54338. return this._loadingDivBackgroundColor;
  54339. },
  54340. set: function (color) {
  54341. this._loadingDivBackgroundColor = color;
  54342. if (!this._loadingDiv) {
  54343. return;
  54344. }
  54345. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  54346. },
  54347. enumerable: true,
  54348. configurable: true
  54349. });
  54350. return DefaultLoadingScreen;
  54351. }());
  54352. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  54353. })(BABYLON || (BABYLON = {}));
  54354. //# sourceMappingURL=babylon.loadingScreen.js.map
  54355. var BABYLON;
  54356. (function (BABYLON) {
  54357. var SceneLoaderProgressEvent = /** @class */ (function () {
  54358. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  54359. this.lengthComputable = lengthComputable;
  54360. this.loaded = loaded;
  54361. this.total = total;
  54362. }
  54363. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  54364. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  54365. };
  54366. return SceneLoaderProgressEvent;
  54367. }());
  54368. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  54369. var SceneLoader = /** @class */ (function () {
  54370. function SceneLoader() {
  54371. }
  54372. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  54373. get: function () {
  54374. return 0;
  54375. },
  54376. enumerable: true,
  54377. configurable: true
  54378. });
  54379. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  54380. get: function () {
  54381. return 1;
  54382. },
  54383. enumerable: true,
  54384. configurable: true
  54385. });
  54386. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  54387. get: function () {
  54388. return 2;
  54389. },
  54390. enumerable: true,
  54391. configurable: true
  54392. });
  54393. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  54394. get: function () {
  54395. return 3;
  54396. },
  54397. enumerable: true,
  54398. configurable: true
  54399. });
  54400. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  54401. get: function () {
  54402. return SceneLoader._ForceFullSceneLoadingForIncremental;
  54403. },
  54404. set: function (value) {
  54405. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  54406. },
  54407. enumerable: true,
  54408. configurable: true
  54409. });
  54410. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  54411. get: function () {
  54412. return SceneLoader._ShowLoadingScreen;
  54413. },
  54414. set: function (value) {
  54415. SceneLoader._ShowLoadingScreen = value;
  54416. },
  54417. enumerable: true,
  54418. configurable: true
  54419. });
  54420. Object.defineProperty(SceneLoader, "loggingLevel", {
  54421. get: function () {
  54422. return SceneLoader._loggingLevel;
  54423. },
  54424. set: function (value) {
  54425. SceneLoader._loggingLevel = value;
  54426. },
  54427. enumerable: true,
  54428. configurable: true
  54429. });
  54430. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  54431. get: function () {
  54432. return SceneLoader._CleanBoneMatrixWeights;
  54433. },
  54434. set: function (value) {
  54435. SceneLoader._CleanBoneMatrixWeights = value;
  54436. },
  54437. enumerable: true,
  54438. configurable: true
  54439. });
  54440. SceneLoader._getDefaultPlugin = function () {
  54441. return SceneLoader._registeredPlugins[".babylon"];
  54442. };
  54443. SceneLoader._getPluginForExtension = function (extension) {
  54444. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  54445. if (registeredPlugin) {
  54446. return registeredPlugin;
  54447. }
  54448. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  54449. return SceneLoader._getDefaultPlugin();
  54450. };
  54451. SceneLoader._getPluginForDirectLoad = function (data) {
  54452. for (var extension in SceneLoader._registeredPlugins) {
  54453. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  54454. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  54455. return SceneLoader._registeredPlugins[extension];
  54456. }
  54457. }
  54458. return SceneLoader._getDefaultPlugin();
  54459. };
  54460. SceneLoader._getPluginForFilename = function (sceneFilename) {
  54461. if (sceneFilename.name) {
  54462. sceneFilename = sceneFilename.name;
  54463. }
  54464. var queryStringPosition = sceneFilename.indexOf("?");
  54465. if (queryStringPosition !== -1) {
  54466. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  54467. }
  54468. var dotPosition = sceneFilename.lastIndexOf(".");
  54469. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  54470. return SceneLoader._getPluginForExtension(extension);
  54471. };
  54472. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  54473. SceneLoader._getDirectLoad = function (sceneFilename) {
  54474. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  54475. return sceneFilename.substr(5);
  54476. }
  54477. return null;
  54478. };
  54479. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  54480. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  54481. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  54482. var plugin;
  54483. if (registeredPlugin.plugin.createPlugin) {
  54484. plugin = registeredPlugin.plugin.createPlugin();
  54485. }
  54486. else {
  54487. plugin = registeredPlugin.plugin;
  54488. }
  54489. var useArrayBuffer = registeredPlugin.isBinary;
  54490. var database;
  54491. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  54492. var dataCallback = function (data, responseURL) {
  54493. if (scene.isDisposed) {
  54494. onError("Scene has been disposed");
  54495. return;
  54496. }
  54497. scene.database = database;
  54498. onSuccess(plugin, data, responseURL);
  54499. };
  54500. var request = null;
  54501. var pluginDisposed = false;
  54502. var onDisposeObservable = plugin.onDisposeObservable;
  54503. if (onDisposeObservable) {
  54504. onDisposeObservable.add(function () {
  54505. pluginDisposed = true;
  54506. if (request) {
  54507. request.abort();
  54508. request = null;
  54509. }
  54510. onDispose();
  54511. });
  54512. }
  54513. var manifestChecked = function () {
  54514. if (pluginDisposed) {
  54515. return;
  54516. }
  54517. var url = rootUrl + sceneFilename;
  54518. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  54519. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  54520. } : undefined, database, useArrayBuffer, function (request, exception) {
  54521. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  54522. });
  54523. };
  54524. if (directLoad) {
  54525. dataCallback(directLoad);
  54526. return plugin;
  54527. }
  54528. if (rootUrl.indexOf("file:") === -1) {
  54529. if (scene.getEngine().enableOfflineSupport) {
  54530. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  54531. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  54532. }
  54533. else {
  54534. manifestChecked();
  54535. }
  54536. }
  54537. else {
  54538. var fileOrString = sceneFilename;
  54539. if (fileOrString.name) {
  54540. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  54541. }
  54542. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  54543. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  54544. }
  54545. else {
  54546. onError("Unable to find file named " + sceneFilename);
  54547. }
  54548. }
  54549. return plugin;
  54550. };
  54551. // Public functions
  54552. SceneLoader.GetPluginForExtension = function (extension) {
  54553. return SceneLoader._getPluginForExtension(extension).plugin;
  54554. };
  54555. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  54556. return !!SceneLoader._registeredPlugins[extension];
  54557. };
  54558. SceneLoader.RegisterPlugin = function (plugin) {
  54559. if (typeof plugin.extensions === "string") {
  54560. var extension = plugin.extensions;
  54561. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54562. plugin: plugin,
  54563. isBinary: false
  54564. };
  54565. }
  54566. else {
  54567. var extensions = plugin.extensions;
  54568. Object.keys(extensions).forEach(function (extension) {
  54569. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54570. plugin: plugin,
  54571. isBinary: extensions[extension].isBinary
  54572. };
  54573. });
  54574. }
  54575. };
  54576. /**
  54577. * Import meshes into a scene
  54578. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  54579. * @param rootUrl a string that defines the root url for scene and resources
  54580. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54581. * @param scene the instance of BABYLON.Scene to append to
  54582. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  54583. * @param onProgress a callback with a progress event for each file being loaded
  54584. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54585. */
  54586. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54587. if (onSuccess === void 0) { onSuccess = null; }
  54588. if (onProgress === void 0) { onProgress = null; }
  54589. if (onError === void 0) { onError = null; }
  54590. if (pluginExtension === void 0) { pluginExtension = null; }
  54591. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54592. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54593. return null;
  54594. }
  54595. var loadingToken = {};
  54596. scene._addPendingData(loadingToken);
  54597. var disposeHandler = function () {
  54598. scene._removePendingData(loadingToken);
  54599. };
  54600. var errorHandler = function (message, exception) {
  54601. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  54602. if (onError) {
  54603. onError(scene, errorMessage, exception);
  54604. }
  54605. else {
  54606. BABYLON.Tools.Error(errorMessage);
  54607. // should the exception be thrown?
  54608. }
  54609. disposeHandler();
  54610. };
  54611. var progressHandler = onProgress ? function (event) {
  54612. try {
  54613. onProgress(event);
  54614. }
  54615. catch (e) {
  54616. errorHandler("Error in onProgress callback", e);
  54617. }
  54618. } : undefined;
  54619. var successHandler = function (meshes, particleSystems, skeletons) {
  54620. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  54621. if (onSuccess) {
  54622. try {
  54623. onSuccess(meshes, particleSystems, skeletons);
  54624. }
  54625. catch (e) {
  54626. errorHandler("Error in onSuccess callback", e);
  54627. }
  54628. }
  54629. scene._removePendingData(loadingToken);
  54630. };
  54631. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54632. if (plugin.rewriteRootURL) {
  54633. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  54634. }
  54635. if (plugin.importMesh) {
  54636. var syncedPlugin = plugin;
  54637. var meshes = new Array();
  54638. var particleSystems = new Array();
  54639. var skeletons = new Array();
  54640. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  54641. return;
  54642. }
  54643. scene.loadingPluginName = plugin.name;
  54644. successHandler(meshes, particleSystems, skeletons);
  54645. }
  54646. else {
  54647. var asyncedPlugin = plugin;
  54648. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  54649. scene.loadingPluginName = plugin.name;
  54650. successHandler(meshes, particleSystems, skeletons);
  54651. }, progressHandler, errorHandler);
  54652. }
  54653. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54654. };
  54655. /**
  54656. * Load a scene
  54657. * @param rootUrl a string that defines the root url for scene and resources
  54658. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54659. * @param engine is the instance of BABYLON.Engine to use to create the scene
  54660. * @param onSuccess a callback with the scene when import succeeds
  54661. * @param onProgress a callback with a progress event for each file being loaded
  54662. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54663. */
  54664. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  54665. if (onSuccess === void 0) { onSuccess = null; }
  54666. if (onProgress === void 0) { onProgress = null; }
  54667. if (onError === void 0) { onError = null; }
  54668. if (pluginExtension === void 0) { pluginExtension = null; }
  54669. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  54670. };
  54671. /**
  54672. * Append a scene
  54673. * @param rootUrl a string that defines the root url for scene and resources
  54674. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54675. * @param scene is the instance of BABYLON.Scene to append to
  54676. * @param onSuccess a callback with the scene when import succeeds
  54677. * @param onProgress a callback with a progress event for each file being loaded
  54678. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54679. */
  54680. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54681. if (onSuccess === void 0) { onSuccess = null; }
  54682. if (onProgress === void 0) { onProgress = null; }
  54683. if (onError === void 0) { onError = null; }
  54684. if (pluginExtension === void 0) { pluginExtension = null; }
  54685. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54686. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54687. return null;
  54688. }
  54689. if (SceneLoader.ShowLoadingScreen) {
  54690. scene.getEngine().displayLoadingUI();
  54691. }
  54692. var loadingToken = {};
  54693. scene._addPendingData(loadingToken);
  54694. var disposeHandler = function () {
  54695. scene._removePendingData(loadingToken);
  54696. scene.getEngine().hideLoadingUI();
  54697. };
  54698. var errorHandler = function (message, exception) {
  54699. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  54700. if (onError) {
  54701. onError(scene, errorMessage, exception);
  54702. }
  54703. else {
  54704. BABYLON.Tools.Error(errorMessage);
  54705. // should the exception be thrown?
  54706. }
  54707. disposeHandler();
  54708. };
  54709. var progressHandler = onProgress ? function (event) {
  54710. try {
  54711. onProgress(event);
  54712. }
  54713. catch (e) {
  54714. errorHandler("Error in onProgress callback", e);
  54715. }
  54716. } : undefined;
  54717. var successHandler = function () {
  54718. if (onSuccess) {
  54719. try {
  54720. onSuccess(scene);
  54721. }
  54722. catch (e) {
  54723. errorHandler("Error in onSuccess callback", e);
  54724. }
  54725. }
  54726. scene._removePendingData(loadingToken);
  54727. };
  54728. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54729. if (plugin.load) {
  54730. var syncedPlugin = plugin;
  54731. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  54732. return;
  54733. }
  54734. scene.loadingPluginName = plugin.name;
  54735. successHandler();
  54736. }
  54737. else {
  54738. var asyncedPlugin = plugin;
  54739. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  54740. scene.loadingPluginName = plugin.name;
  54741. successHandler();
  54742. }, progressHandler, errorHandler);
  54743. }
  54744. if (SceneLoader.ShowLoadingScreen) {
  54745. scene.executeWhenReady(function () {
  54746. scene.getEngine().hideLoadingUI();
  54747. });
  54748. }
  54749. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54750. };
  54751. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54752. if (onSuccess === void 0) { onSuccess = null; }
  54753. if (onProgress === void 0) { onProgress = null; }
  54754. if (onError === void 0) { onError = null; }
  54755. if (pluginExtension === void 0) { pluginExtension = null; }
  54756. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54757. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54758. return null;
  54759. }
  54760. var loadingToken = {};
  54761. scene._addPendingData(loadingToken);
  54762. var disposeHandler = function () {
  54763. scene._removePendingData(loadingToken);
  54764. };
  54765. var errorHandler = function (message, exception) {
  54766. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  54767. if (onError) {
  54768. onError(scene, errorMessage, exception);
  54769. }
  54770. else {
  54771. BABYLON.Tools.Error(errorMessage);
  54772. // should the exception be thrown?
  54773. }
  54774. disposeHandler();
  54775. };
  54776. var progressHandler = onProgress ? function (event) {
  54777. try {
  54778. onProgress(event);
  54779. }
  54780. catch (e) {
  54781. errorHandler("Error in onProgress callback", e);
  54782. }
  54783. } : undefined;
  54784. var successHandler = function (assets) {
  54785. if (onSuccess) {
  54786. try {
  54787. onSuccess(assets);
  54788. }
  54789. catch (e) {
  54790. errorHandler("Error in onSuccess callback", e);
  54791. }
  54792. }
  54793. scene._removePendingData(loadingToken);
  54794. };
  54795. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54796. if (plugin.loadAssets) {
  54797. var syncedPlugin = plugin;
  54798. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  54799. if (!assetContainer) {
  54800. return;
  54801. }
  54802. scene.loadingPluginName = plugin.name;
  54803. successHandler(assetContainer);
  54804. }
  54805. else if (plugin.loadAssetsAsync) {
  54806. var asyncedPlugin = plugin;
  54807. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  54808. if (assetContainer) {
  54809. scene.loadingPluginName = plugin.name;
  54810. successHandler(assetContainer);
  54811. }
  54812. }, progressHandler, errorHandler);
  54813. }
  54814. else {
  54815. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  54816. }
  54817. if (SceneLoader.ShowLoadingScreen) {
  54818. scene.executeWhenReady(function () {
  54819. scene.getEngine().hideLoadingUI();
  54820. });
  54821. }
  54822. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54823. };
  54824. // Flags
  54825. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  54826. SceneLoader._ShowLoadingScreen = true;
  54827. SceneLoader._CleanBoneMatrixWeights = false;
  54828. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  54829. // Members
  54830. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  54831. SceneLoader._registeredPlugins = {};
  54832. return SceneLoader;
  54833. }());
  54834. BABYLON.SceneLoader = SceneLoader;
  54835. ;
  54836. })(BABYLON || (BABYLON = {}));
  54837. //# sourceMappingURL=babylon.sceneLoader.js.map
  54838. var BABYLON;
  54839. (function (BABYLON) {
  54840. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  54841. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54842. var parsedMaterial = parsedData.materials[index];
  54843. if (parsedMaterial.id === id) {
  54844. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54845. }
  54846. }
  54847. return null;
  54848. };
  54849. var isDescendantOf = function (mesh, names, hierarchyIds) {
  54850. for (var i in names) {
  54851. if (mesh.name === names[i]) {
  54852. hierarchyIds.push(mesh.id);
  54853. return true;
  54854. }
  54855. }
  54856. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  54857. hierarchyIds.push(mesh.id);
  54858. return true;
  54859. }
  54860. return false;
  54861. };
  54862. var logOperation = function (operation, producer) {
  54863. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  54864. };
  54865. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  54866. if (addToScene === void 0) { addToScene = false; }
  54867. var container = new BABYLON.AssetContainer(scene);
  54868. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  54869. // when SceneLoader.debugLogging = true (default), or exception encountered.
  54870. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  54871. // and avoid problems with multiple concurrent .babylon loads.
  54872. var log = "importScene has failed JSON parse";
  54873. try {
  54874. var parsedData = JSON.parse(data);
  54875. log = "";
  54876. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  54877. var index;
  54878. var cache;
  54879. // Lights
  54880. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  54881. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  54882. var parsedLight = parsedData.lights[index];
  54883. var light = BABYLON.Light.Parse(parsedLight, scene);
  54884. if (light) {
  54885. container.lights.push(light);
  54886. log += (index === 0 ? "\n\tLights:" : "");
  54887. log += "\n\t\t" + light.toString(fullDetails);
  54888. }
  54889. }
  54890. }
  54891. // Animations
  54892. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  54893. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  54894. var parsedAnimation = parsedData.animations[index];
  54895. var animation = BABYLON.Animation.Parse(parsedAnimation);
  54896. scene.animations.push(animation);
  54897. container.animations.push(animation);
  54898. log += (index === 0 ? "\n\tAnimations:" : "");
  54899. log += "\n\t\t" + animation.toString(fullDetails);
  54900. }
  54901. }
  54902. // Materials
  54903. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  54904. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54905. var parsedMaterial = parsedData.materials[index];
  54906. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54907. container.materials.push(mat);
  54908. log += (index === 0 ? "\n\tMaterials:" : "");
  54909. log += "\n\t\t" + mat.toString(fullDetails);
  54910. }
  54911. }
  54912. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  54913. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  54914. var parsedMultiMaterial = parsedData.multiMaterials[index];
  54915. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  54916. container.multiMaterials.push(mmat);
  54917. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  54918. log += "\n\t\t" + mmat.toString(fullDetails);
  54919. }
  54920. }
  54921. // Morph targets
  54922. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  54923. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  54924. var managerData = _a[_i];
  54925. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  54926. }
  54927. }
  54928. // Skeletons
  54929. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  54930. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  54931. var parsedSkeleton = parsedData.skeletons[index];
  54932. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  54933. container.skeletons.push(skeleton);
  54934. log += (index === 0 ? "\n\tSkeletons:" : "");
  54935. log += "\n\t\t" + skeleton.toString(fullDetails);
  54936. }
  54937. }
  54938. // Geometries
  54939. var geometries = parsedData.geometries;
  54940. if (geometries !== undefined && geometries !== null) {
  54941. var addedGeometry = new Array();
  54942. // Boxes
  54943. var boxes = geometries.boxes;
  54944. if (boxes !== undefined && boxes !== null) {
  54945. for (index = 0, cache = boxes.length; index < cache; index++) {
  54946. var parsedBox = boxes[index];
  54947. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  54948. }
  54949. }
  54950. // Spheres
  54951. var spheres = geometries.spheres;
  54952. if (spheres !== undefined && spheres !== null) {
  54953. for (index = 0, cache = spheres.length; index < cache; index++) {
  54954. var parsedSphere = spheres[index];
  54955. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  54956. }
  54957. }
  54958. // Cylinders
  54959. var cylinders = geometries.cylinders;
  54960. if (cylinders !== undefined && cylinders !== null) {
  54961. for (index = 0, cache = cylinders.length; index < cache; index++) {
  54962. var parsedCylinder = cylinders[index];
  54963. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  54964. }
  54965. }
  54966. // Toruses
  54967. var toruses = geometries.toruses;
  54968. if (toruses !== undefined && toruses !== null) {
  54969. for (index = 0, cache = toruses.length; index < cache; index++) {
  54970. var parsedTorus = toruses[index];
  54971. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  54972. }
  54973. }
  54974. // Grounds
  54975. var grounds = geometries.grounds;
  54976. if (grounds !== undefined && grounds !== null) {
  54977. for (index = 0, cache = grounds.length; index < cache; index++) {
  54978. var parsedGround = grounds[index];
  54979. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  54980. }
  54981. }
  54982. // Planes
  54983. var planes = geometries.planes;
  54984. if (planes !== undefined && planes !== null) {
  54985. for (index = 0, cache = planes.length; index < cache; index++) {
  54986. var parsedPlane = planes[index];
  54987. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  54988. }
  54989. }
  54990. // TorusKnots
  54991. var torusKnots = geometries.torusKnots;
  54992. if (torusKnots !== undefined && torusKnots !== null) {
  54993. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  54994. var parsedTorusKnot = torusKnots[index];
  54995. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  54996. }
  54997. }
  54998. // VertexData
  54999. var vertexData = geometries.vertexData;
  55000. if (vertexData !== undefined && vertexData !== null) {
  55001. for (index = 0, cache = vertexData.length; index < cache; index++) {
  55002. var parsedVertexData = vertexData[index];
  55003. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  55004. }
  55005. }
  55006. addedGeometry.forEach(function (g) {
  55007. if (g) {
  55008. container.geometries.push(g);
  55009. }
  55010. });
  55011. }
  55012. // Transform nodes
  55013. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  55014. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  55015. var parsedTransformNode = parsedData.transformNodes[index];
  55016. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  55017. container.transformNodes.push(node);
  55018. }
  55019. }
  55020. // Meshes
  55021. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  55022. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  55023. var parsedMesh = parsedData.meshes[index];
  55024. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  55025. container.meshes.push(mesh);
  55026. log += (index === 0 ? "\n\tMeshes:" : "");
  55027. log += "\n\t\t" + mesh.toString(fullDetails);
  55028. }
  55029. }
  55030. // Cameras
  55031. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  55032. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  55033. var parsedCamera = parsedData.cameras[index];
  55034. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  55035. container.cameras.push(camera);
  55036. log += (index === 0 ? "\n\tCameras:" : "");
  55037. log += "\n\t\t" + camera.toString(fullDetails);
  55038. }
  55039. }
  55040. // Browsing all the graph to connect the dots
  55041. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  55042. var camera = scene.cameras[index];
  55043. if (camera._waitingParentId) {
  55044. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  55045. camera._waitingParentId = null;
  55046. }
  55047. }
  55048. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  55049. var light_1 = scene.lights[index];
  55050. if (light_1 && light_1._waitingParentId) {
  55051. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  55052. light_1._waitingParentId = null;
  55053. }
  55054. }
  55055. // Sounds
  55056. // TODO: add sound
  55057. var loadedSounds = [];
  55058. var loadedSound;
  55059. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  55060. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  55061. var parsedSound = parsedData.sounds[index];
  55062. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55063. if (!parsedSound.url)
  55064. parsedSound.url = parsedSound.name;
  55065. if (!loadedSounds[parsedSound.url]) {
  55066. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  55067. loadedSounds[parsedSound.url] = loadedSound;
  55068. container.sounds.push(loadedSound);
  55069. }
  55070. else {
  55071. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  55072. }
  55073. }
  55074. else {
  55075. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  55076. }
  55077. }
  55078. }
  55079. loadedSounds = [];
  55080. // Connect parents & children and parse actions
  55081. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  55082. var transformNode = scene.transformNodes[index];
  55083. if (transformNode._waitingParentId) {
  55084. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  55085. transformNode._waitingParentId = null;
  55086. }
  55087. }
  55088. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55089. var mesh = scene.meshes[index];
  55090. if (mesh._waitingParentId) {
  55091. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  55092. mesh._waitingParentId = null;
  55093. }
  55094. if (mesh._waitingActions) {
  55095. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  55096. mesh._waitingActions = null;
  55097. }
  55098. }
  55099. // freeze world matrix application
  55100. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55101. var currentMesh = scene.meshes[index];
  55102. if (currentMesh._waitingFreezeWorldMatrix) {
  55103. currentMesh.freezeWorldMatrix();
  55104. currentMesh._waitingFreezeWorldMatrix = null;
  55105. }
  55106. else {
  55107. currentMesh.computeWorldMatrix(true);
  55108. }
  55109. }
  55110. // Particles Systems
  55111. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  55112. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  55113. var parsedParticleSystem = parsedData.particleSystems[index];
  55114. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  55115. container.particleSystems.push(ps);
  55116. }
  55117. }
  55118. // Lens flares
  55119. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  55120. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  55121. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  55122. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  55123. container.lensFlareSystems.push(lf);
  55124. }
  55125. }
  55126. // Shadows
  55127. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  55128. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  55129. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  55130. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  55131. container.shadowGenerators.push(sg);
  55132. }
  55133. }
  55134. // Lights exclusions / inclusions
  55135. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  55136. var light_2 = scene.lights[index];
  55137. // Excluded check
  55138. if (light_2._excludedMeshesIds.length > 0) {
  55139. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  55140. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  55141. if (excludedMesh) {
  55142. light_2.excludedMeshes.push(excludedMesh);
  55143. }
  55144. }
  55145. light_2._excludedMeshesIds = [];
  55146. }
  55147. // Included check
  55148. if (light_2._includedOnlyMeshesIds.length > 0) {
  55149. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  55150. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  55151. if (includedOnlyMesh) {
  55152. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  55153. }
  55154. }
  55155. light_2._includedOnlyMeshesIds = [];
  55156. }
  55157. }
  55158. // Actions (scene)
  55159. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  55160. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  55161. }
  55162. if (!addToScene) {
  55163. container.removeAllFromScene();
  55164. }
  55165. return container;
  55166. }
  55167. catch (err) {
  55168. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  55169. if (onError) {
  55170. onError(msg, err);
  55171. }
  55172. else {
  55173. BABYLON.Tools.Log(msg);
  55174. throw err;
  55175. }
  55176. }
  55177. finally {
  55178. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55179. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55180. }
  55181. }
  55182. return null;
  55183. };
  55184. BABYLON.SceneLoader.RegisterPlugin({
  55185. name: "babylon.js",
  55186. extensions: ".babylon",
  55187. canDirectLoad: function (data) {
  55188. if (data.indexOf("babylon") !== -1) {
  55189. return true;
  55190. }
  55191. return false;
  55192. },
  55193. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  55194. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  55195. // when SceneLoader.debugLogging = true (default), or exception encountered.
  55196. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  55197. // and avoid problems with multiple concurrent .babylon loads.
  55198. var log = "importMesh has failed JSON parse";
  55199. try {
  55200. var parsedData = JSON.parse(data);
  55201. log = "";
  55202. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  55203. if (!meshesNames) {
  55204. meshesNames = null;
  55205. }
  55206. else if (!Array.isArray(meshesNames)) {
  55207. meshesNames = [meshesNames];
  55208. }
  55209. var hierarchyIds = new Array();
  55210. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  55211. var loadedSkeletonsIds = [];
  55212. var loadedMaterialsIds = [];
  55213. var index;
  55214. var cache;
  55215. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  55216. var parsedMesh = parsedData.meshes[index];
  55217. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  55218. if (meshesNames !== null) {
  55219. // Remove found mesh name from list.
  55220. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  55221. }
  55222. //Geometry?
  55223. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  55224. //does the file contain geometries?
  55225. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  55226. //find the correct geometry and add it to the scene
  55227. var found = false;
  55228. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  55229. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  55230. return;
  55231. }
  55232. else {
  55233. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  55234. if (parsedGeometryData.id === parsedMesh.geometryId) {
  55235. switch (geometryType) {
  55236. case "boxes":
  55237. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  55238. break;
  55239. case "spheres":
  55240. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  55241. break;
  55242. case "cylinders":
  55243. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  55244. break;
  55245. case "toruses":
  55246. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  55247. break;
  55248. case "grounds":
  55249. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  55250. break;
  55251. case "planes":
  55252. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  55253. break;
  55254. case "torusKnots":
  55255. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  55256. break;
  55257. case "vertexData":
  55258. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  55259. break;
  55260. }
  55261. found = true;
  55262. }
  55263. });
  55264. }
  55265. });
  55266. if (found === false) {
  55267. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  55268. }
  55269. }
  55270. }
  55271. // Material ?
  55272. if (parsedMesh.materialId) {
  55273. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  55274. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  55275. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  55276. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  55277. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  55278. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  55279. var subMatId = parsedMultiMaterial.materials[matIndex];
  55280. loadedMaterialsIds.push(subMatId);
  55281. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  55282. log += "\n\tMaterial " + mat.toString(fullDetails);
  55283. }
  55284. loadedMaterialsIds.push(parsedMultiMaterial.id);
  55285. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  55286. materialFound = true;
  55287. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  55288. break;
  55289. }
  55290. }
  55291. }
  55292. if (materialFound === false) {
  55293. loadedMaterialsIds.push(parsedMesh.materialId);
  55294. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  55295. if (!mat) {
  55296. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  55297. }
  55298. else {
  55299. log += "\n\tMaterial " + mat.toString(fullDetails);
  55300. }
  55301. }
  55302. }
  55303. // Skeleton ?
  55304. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  55305. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  55306. if (skeletonAlreadyLoaded === false) {
  55307. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  55308. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  55309. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  55310. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  55311. skeletons.push(skeleton);
  55312. loadedSkeletonsIds.push(parsedSkeleton.id);
  55313. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  55314. }
  55315. }
  55316. }
  55317. }
  55318. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  55319. meshes.push(mesh);
  55320. log += "\n\tMesh " + mesh.toString(fullDetails);
  55321. }
  55322. }
  55323. // Connecting parents
  55324. var currentMesh;
  55325. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55326. currentMesh = scene.meshes[index];
  55327. if (currentMesh._waitingParentId) {
  55328. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  55329. currentMesh._waitingParentId = null;
  55330. }
  55331. }
  55332. // freeze and compute world matrix application
  55333. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55334. currentMesh = scene.meshes[index];
  55335. if (currentMesh._waitingFreezeWorldMatrix) {
  55336. currentMesh.freezeWorldMatrix();
  55337. currentMesh._waitingFreezeWorldMatrix = null;
  55338. }
  55339. else {
  55340. currentMesh.computeWorldMatrix(true);
  55341. }
  55342. }
  55343. }
  55344. // Particles
  55345. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  55346. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  55347. var parsedParticleSystem = parsedData.particleSystems[index];
  55348. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  55349. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  55350. }
  55351. }
  55352. }
  55353. return true;
  55354. }
  55355. catch (err) {
  55356. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  55357. if (onError) {
  55358. onError(msg, err);
  55359. }
  55360. else {
  55361. BABYLON.Tools.Log(msg);
  55362. throw err;
  55363. }
  55364. }
  55365. finally {
  55366. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55367. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55368. }
  55369. }
  55370. return false;
  55371. },
  55372. load: function (scene, data, rootUrl, onError) {
  55373. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  55374. // when SceneLoader.debugLogging = true (default), or exception encountered.
  55375. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  55376. // and avoid problems with multiple concurrent .babylon loads.
  55377. var log = "importScene has failed JSON parse";
  55378. try {
  55379. var parsedData = JSON.parse(data);
  55380. log = "";
  55381. // Scene
  55382. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  55383. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  55384. }
  55385. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  55386. scene.autoClear = parsedData.autoClear;
  55387. }
  55388. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  55389. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  55390. }
  55391. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  55392. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  55393. }
  55394. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  55395. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  55396. }
  55397. // Fog
  55398. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  55399. scene.fogMode = parsedData.fogMode;
  55400. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  55401. scene.fogStart = parsedData.fogStart;
  55402. scene.fogEnd = parsedData.fogEnd;
  55403. scene.fogDensity = parsedData.fogDensity;
  55404. log += "\tFog mode for scene: ";
  55405. switch (scene.fogMode) {
  55406. // getters not compiling, so using hardcoded
  55407. case 1:
  55408. log += "exp\n";
  55409. break;
  55410. case 2:
  55411. log += "exp2\n";
  55412. break;
  55413. case 3:
  55414. log += "linear\n";
  55415. break;
  55416. }
  55417. }
  55418. //Physics
  55419. if (parsedData.physicsEnabled) {
  55420. var physicsPlugin;
  55421. if (parsedData.physicsEngine === "cannon") {
  55422. physicsPlugin = new BABYLON.CannonJSPlugin();
  55423. }
  55424. else if (parsedData.physicsEngine === "oimo") {
  55425. physicsPlugin = new BABYLON.OimoJSPlugin();
  55426. }
  55427. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  55428. //else - default engine, which is currently oimo
  55429. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  55430. scene.enablePhysics(physicsGravity, physicsPlugin);
  55431. }
  55432. // Metadata
  55433. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  55434. scene.metadata = parsedData.metadata;
  55435. }
  55436. //collisions, if defined. otherwise, default is true
  55437. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  55438. scene.collisionsEnabled = parsedData.collisionsEnabled;
  55439. }
  55440. scene.workerCollisions = !!parsedData.workerCollisions;
  55441. var container = loadAssets(scene, data, rootUrl, onerror, true);
  55442. if (!container) {
  55443. return false;
  55444. }
  55445. if (parsedData.autoAnimate) {
  55446. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  55447. }
  55448. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  55449. scene.setActiveCameraByID(parsedData.activeCameraID);
  55450. }
  55451. // Environment texture
  55452. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  55453. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  55454. if (parsedData.createDefaultSkybox === true) {
  55455. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  55456. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  55457. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  55458. }
  55459. }
  55460. // Finish
  55461. return true;
  55462. }
  55463. catch (err) {
  55464. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  55465. if (onError) {
  55466. onError(msg, err);
  55467. }
  55468. else {
  55469. BABYLON.Tools.Log(msg);
  55470. throw err;
  55471. }
  55472. }
  55473. finally {
  55474. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55475. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55476. }
  55477. }
  55478. return false;
  55479. },
  55480. loadAssets: function (scene, data, rootUrl, onError) {
  55481. var container = loadAssets(scene, data, rootUrl, onerror);
  55482. return container;
  55483. }
  55484. });
  55485. })(BABYLON || (BABYLON = {}));
  55486. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  55487. var BABYLON;
  55488. (function (BABYLON) {
  55489. var FilesInput = /** @class */ (function () {
  55490. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  55491. this.onProcessFileCallback = function () { return true; };
  55492. this._engine = engine;
  55493. this._currentScene = scene;
  55494. this._sceneLoadedCallback = sceneLoadedCallback;
  55495. this._progressCallback = progressCallback;
  55496. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  55497. this._textureLoadingCallback = textureLoadingCallback;
  55498. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  55499. this._onReloadCallback = onReloadCallback;
  55500. this._errorCallback = errorCallback;
  55501. }
  55502. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  55503. var _this = this;
  55504. if (elementToMonitor) {
  55505. this._elementToMonitor = elementToMonitor;
  55506. this._dragEnterHandler = function (e) { _this.drag(e); };
  55507. this._dragOverHandler = function (e) { _this.drag(e); };
  55508. this._dropHandler = function (e) { _this.drop(e); };
  55509. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  55510. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  55511. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  55512. }
  55513. };
  55514. FilesInput.prototype.dispose = function () {
  55515. if (!this._elementToMonitor) {
  55516. return;
  55517. }
  55518. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  55519. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  55520. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  55521. };
  55522. FilesInput.prototype.renderFunction = function () {
  55523. if (this._additionalRenderLoopLogicCallback) {
  55524. this._additionalRenderLoopLogicCallback();
  55525. }
  55526. if (this._currentScene) {
  55527. if (this._textureLoadingCallback) {
  55528. var remaining = this._currentScene.getWaitingItemsCount();
  55529. if (remaining > 0) {
  55530. this._textureLoadingCallback(remaining);
  55531. }
  55532. }
  55533. this._currentScene.render();
  55534. }
  55535. };
  55536. FilesInput.prototype.drag = function (e) {
  55537. e.stopPropagation();
  55538. e.preventDefault();
  55539. };
  55540. FilesInput.prototype.drop = function (eventDrop) {
  55541. eventDrop.stopPropagation();
  55542. eventDrop.preventDefault();
  55543. this.loadFiles(eventDrop);
  55544. };
  55545. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  55546. var _this = this;
  55547. var reader = folder.createReader();
  55548. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  55549. reader.readEntries(function (entries) {
  55550. remaining.count += entries.length;
  55551. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  55552. var entry = entries_1[_i];
  55553. if (entry.isFile) {
  55554. entry.file(function (file) {
  55555. file.correctName = relativePath + file.name;
  55556. files.push(file);
  55557. if (--remaining.count === 0) {
  55558. callback();
  55559. }
  55560. });
  55561. }
  55562. else if (entry.isDirectory) {
  55563. _this._traverseFolder(entry, files, remaining, callback);
  55564. }
  55565. }
  55566. if (--remaining.count) {
  55567. callback();
  55568. }
  55569. });
  55570. };
  55571. FilesInput.prototype._processFiles = function (files) {
  55572. for (var i = 0; i < files.length; i++) {
  55573. var name = files[i].correctName.toLowerCase();
  55574. var extension = name.split('.').pop();
  55575. if (!this.onProcessFileCallback(files[i], name, extension)) {
  55576. continue;
  55577. }
  55578. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  55579. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  55580. this._sceneFileToLoad = files[i];
  55581. }
  55582. else {
  55583. FilesInput.FilesToLoad[name] = files[i];
  55584. }
  55585. }
  55586. };
  55587. FilesInput.prototype.loadFiles = function (event) {
  55588. var _this = this;
  55589. if (this._startingProcessingFilesCallback)
  55590. this._startingProcessingFilesCallback();
  55591. // Handling data transfer via drag'n'drop
  55592. if (event && event.dataTransfer && event.dataTransfer.files) {
  55593. this._filesToLoad = event.dataTransfer.files;
  55594. }
  55595. // Handling files from input files
  55596. if (event && event.target && event.target.files) {
  55597. this._filesToLoad = event.target.files;
  55598. }
  55599. if (this._filesToLoad && this._filesToLoad.length > 0) {
  55600. var files_1 = new Array();
  55601. var folders = [];
  55602. var items = event.dataTransfer ? event.dataTransfer.items : null;
  55603. for (var i = 0; i < this._filesToLoad.length; i++) {
  55604. var fileToLoad = this._filesToLoad[i];
  55605. var name_1 = fileToLoad.name.toLowerCase();
  55606. var entry = void 0;
  55607. fileToLoad.correctName = name_1;
  55608. if (items) {
  55609. var item = items[i];
  55610. if (item.getAsEntry) {
  55611. entry = item.getAsEntry();
  55612. }
  55613. else if (item.webkitGetAsEntry) {
  55614. entry = item.webkitGetAsEntry();
  55615. }
  55616. }
  55617. if (!entry) {
  55618. files_1.push(fileToLoad);
  55619. }
  55620. else {
  55621. if (entry.isDirectory) {
  55622. folders.push(entry);
  55623. }
  55624. else {
  55625. files_1.push(fileToLoad);
  55626. }
  55627. }
  55628. }
  55629. if (folders.length === 0) {
  55630. this._processFiles(files_1);
  55631. this._processReload();
  55632. }
  55633. else {
  55634. var remaining = { count: folders.length };
  55635. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  55636. var folder = folders_1[_i];
  55637. this._traverseFolder(folder, files_1, remaining, function () {
  55638. _this._processFiles(files_1);
  55639. if (remaining.count === 0) {
  55640. _this._processReload();
  55641. }
  55642. });
  55643. }
  55644. }
  55645. }
  55646. };
  55647. FilesInput.prototype._processReload = function () {
  55648. if (this._onReloadCallback) {
  55649. this._onReloadCallback(this._sceneFileToLoad);
  55650. }
  55651. else {
  55652. this.reload();
  55653. }
  55654. };
  55655. FilesInput.prototype.reload = function () {
  55656. var _this = this;
  55657. // If a scene file has been provided
  55658. if (this._sceneFileToLoad) {
  55659. if (this._currentScene) {
  55660. if (BABYLON.Tools.errorsCount > 0) {
  55661. BABYLON.Tools.ClearLogCache();
  55662. }
  55663. this._engine.stopRenderLoop();
  55664. this._currentScene.dispose();
  55665. }
  55666. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  55667. _this._currentScene = newScene;
  55668. if (_this._sceneLoadedCallback) {
  55669. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  55670. }
  55671. // Wait for textures and shaders to be ready
  55672. _this._currentScene.executeWhenReady(function () {
  55673. _this._engine.runRenderLoop(function () {
  55674. _this.renderFunction();
  55675. });
  55676. });
  55677. }, function (progress) {
  55678. if (_this._progressCallback) {
  55679. _this._progressCallback(progress);
  55680. }
  55681. }, function (scene, message) {
  55682. _this._currentScene = scene;
  55683. if (_this._errorCallback) {
  55684. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  55685. }
  55686. });
  55687. }
  55688. else {
  55689. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  55690. }
  55691. };
  55692. FilesInput.FilesToLoad = {};
  55693. return FilesInput;
  55694. }());
  55695. BABYLON.FilesInput = FilesInput;
  55696. })(BABYLON || (BABYLON = {}));
  55697. //# sourceMappingURL=babylon.filesInput.js.map
  55698. var BABYLON;
  55699. (function (BABYLON) {
  55700. /**
  55701. * This class implement a typical dictionary using a string as key and the generic type T as value.
  55702. * The underlying implementation relies on an associative array to ensure the best performances.
  55703. * The value can be anything including 'null' but except 'undefined'
  55704. */
  55705. var StringDictionary = /** @class */ (function () {
  55706. function StringDictionary() {
  55707. this._count = 0;
  55708. this._data = {};
  55709. }
  55710. /**
  55711. * This will clear this dictionary and copy the content from the 'source' one.
  55712. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  55713. * @param source the dictionary to take the content from and copy to this dictionary
  55714. */
  55715. StringDictionary.prototype.copyFrom = function (source) {
  55716. var _this = this;
  55717. this.clear();
  55718. source.forEach(function (t, v) { return _this.add(t, v); });
  55719. };
  55720. /**
  55721. * Get a value based from its key
  55722. * @param key the given key to get the matching value from
  55723. * @return the value if found, otherwise undefined is returned
  55724. */
  55725. StringDictionary.prototype.get = function (key) {
  55726. var val = this._data[key];
  55727. if (val !== undefined) {
  55728. return val;
  55729. }
  55730. return undefined;
  55731. };
  55732. /**
  55733. * Get a value from its key or add it if it doesn't exist.
  55734. * This method will ensure you that a given key/data will be present in the dictionary.
  55735. * @param key the given key to get the matching value from
  55736. * @param factory the factory that will create the value if the key is not present in the dictionary.
  55737. * The factory will only be invoked if there's no data for the given key.
  55738. * @return the value corresponding to the key.
  55739. */
  55740. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  55741. var val = this.get(key);
  55742. if (val !== undefined) {
  55743. return val;
  55744. }
  55745. val = factory(key);
  55746. if (val) {
  55747. this.add(key, val);
  55748. }
  55749. return val;
  55750. };
  55751. /**
  55752. * Get a value from its key if present in the dictionary otherwise add it
  55753. * @param key the key to get the value from
  55754. * @param val if there's no such key/value pair in the dictionary add it with this value
  55755. * @return the value corresponding to the key
  55756. */
  55757. StringDictionary.prototype.getOrAdd = function (key, val) {
  55758. var curVal = this.get(key);
  55759. if (curVal !== undefined) {
  55760. return curVal;
  55761. }
  55762. this.add(key, val);
  55763. return val;
  55764. };
  55765. /**
  55766. * Check if there's a given key in the dictionary
  55767. * @param key the key to check for
  55768. * @return true if the key is present, false otherwise
  55769. */
  55770. StringDictionary.prototype.contains = function (key) {
  55771. return this._data[key] !== undefined;
  55772. };
  55773. /**
  55774. * Add a new key and its corresponding value
  55775. * @param key the key to add
  55776. * @param value the value corresponding to the key
  55777. * @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
  55778. */
  55779. StringDictionary.prototype.add = function (key, value) {
  55780. if (this._data[key] !== undefined) {
  55781. return false;
  55782. }
  55783. this._data[key] = value;
  55784. ++this._count;
  55785. return true;
  55786. };
  55787. StringDictionary.prototype.set = function (key, value) {
  55788. if (this._data[key] === undefined) {
  55789. return false;
  55790. }
  55791. this._data[key] = value;
  55792. return true;
  55793. };
  55794. /**
  55795. * Get the element of the given key and remove it from the dictionary
  55796. * @param key
  55797. */
  55798. StringDictionary.prototype.getAndRemove = function (key) {
  55799. var val = this.get(key);
  55800. if (val !== undefined) {
  55801. delete this._data[key];
  55802. --this._count;
  55803. return val;
  55804. }
  55805. return null;
  55806. };
  55807. /**
  55808. * Remove a key/value from the dictionary.
  55809. * @param key the key to remove
  55810. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  55811. */
  55812. StringDictionary.prototype.remove = function (key) {
  55813. if (this.contains(key)) {
  55814. delete this._data[key];
  55815. --this._count;
  55816. return true;
  55817. }
  55818. return false;
  55819. };
  55820. /**
  55821. * Clear the whole content of the dictionary
  55822. */
  55823. StringDictionary.prototype.clear = function () {
  55824. this._data = {};
  55825. this._count = 0;
  55826. };
  55827. Object.defineProperty(StringDictionary.prototype, "count", {
  55828. get: function () {
  55829. return this._count;
  55830. },
  55831. enumerable: true,
  55832. configurable: true
  55833. });
  55834. /**
  55835. * Execute a callback on each key/val of the dictionary.
  55836. * Note that you can remove any element in this dictionary in the callback implementation
  55837. * @param callback the callback to execute on a given key/value pair
  55838. */
  55839. StringDictionary.prototype.forEach = function (callback) {
  55840. for (var cur in this._data) {
  55841. var val = this._data[cur];
  55842. callback(cur, val);
  55843. }
  55844. };
  55845. /**
  55846. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  55847. * If the callback returns null or undefined the method will iterate to the next key/value pair
  55848. * Note that you can remove any element in this dictionary in the callback implementation
  55849. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  55850. */
  55851. StringDictionary.prototype.first = function (callback) {
  55852. for (var cur in this._data) {
  55853. var val = this._data[cur];
  55854. var res = callback(cur, val);
  55855. if (res) {
  55856. return res;
  55857. }
  55858. }
  55859. return null;
  55860. };
  55861. return StringDictionary;
  55862. }());
  55863. BABYLON.StringDictionary = StringDictionary;
  55864. })(BABYLON || (BABYLON = {}));
  55865. //# sourceMappingURL=babylon.stringDictionary.js.map
  55866. var BABYLON;
  55867. (function (BABYLON) {
  55868. var Tags = /** @class */ (function () {
  55869. function Tags() {
  55870. }
  55871. Tags.EnableFor = function (obj) {
  55872. obj._tags = obj._tags || {};
  55873. obj.hasTags = function () {
  55874. return Tags.HasTags(obj);
  55875. };
  55876. obj.addTags = function (tagsString) {
  55877. return Tags.AddTagsTo(obj, tagsString);
  55878. };
  55879. obj.removeTags = function (tagsString) {
  55880. return Tags.RemoveTagsFrom(obj, tagsString);
  55881. };
  55882. obj.matchesTagsQuery = function (tagsQuery) {
  55883. return Tags.MatchesQuery(obj, tagsQuery);
  55884. };
  55885. };
  55886. Tags.DisableFor = function (obj) {
  55887. delete obj._tags;
  55888. delete obj.hasTags;
  55889. delete obj.addTags;
  55890. delete obj.removeTags;
  55891. delete obj.matchesTagsQuery;
  55892. };
  55893. Tags.HasTags = function (obj) {
  55894. if (!obj._tags) {
  55895. return false;
  55896. }
  55897. return !BABYLON.Tools.IsEmpty(obj._tags);
  55898. };
  55899. Tags.GetTags = function (obj, asString) {
  55900. if (asString === void 0) { asString = true; }
  55901. if (!obj._tags) {
  55902. return null;
  55903. }
  55904. if (asString) {
  55905. var tagsArray = [];
  55906. for (var tag in obj._tags) {
  55907. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  55908. tagsArray.push(tag);
  55909. }
  55910. }
  55911. return tagsArray.join(" ");
  55912. }
  55913. else {
  55914. return obj._tags;
  55915. }
  55916. };
  55917. // the tags 'true' and 'false' are reserved and cannot be used as tags
  55918. // a tag cannot start with '||', '&&', and '!'
  55919. // it cannot contain whitespaces
  55920. Tags.AddTagsTo = function (obj, tagsString) {
  55921. if (!tagsString) {
  55922. return;
  55923. }
  55924. if (typeof tagsString !== "string") {
  55925. return;
  55926. }
  55927. var tags = tagsString.split(" ");
  55928. tags.forEach(function (tag, index, array) {
  55929. Tags._AddTagTo(obj, tag);
  55930. });
  55931. };
  55932. Tags._AddTagTo = function (obj, tag) {
  55933. tag = tag.trim();
  55934. if (tag === "" || tag === "true" || tag === "false") {
  55935. return;
  55936. }
  55937. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  55938. return;
  55939. }
  55940. Tags.EnableFor(obj);
  55941. obj._tags[tag] = true;
  55942. };
  55943. Tags.RemoveTagsFrom = function (obj, tagsString) {
  55944. if (!Tags.HasTags(obj)) {
  55945. return;
  55946. }
  55947. var tags = tagsString.split(" ");
  55948. for (var t in tags) {
  55949. Tags._RemoveTagFrom(obj, tags[t]);
  55950. }
  55951. };
  55952. Tags._RemoveTagFrom = function (obj, tag) {
  55953. delete obj._tags[tag];
  55954. };
  55955. Tags.MatchesQuery = function (obj, tagsQuery) {
  55956. if (tagsQuery === undefined) {
  55957. return true;
  55958. }
  55959. if (tagsQuery === "") {
  55960. return Tags.HasTags(obj);
  55961. }
  55962. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  55963. };
  55964. return Tags;
  55965. }());
  55966. BABYLON.Tags = Tags;
  55967. })(BABYLON || (BABYLON = {}));
  55968. //# sourceMappingURL=babylon.tags.js.map
  55969. var BABYLON;
  55970. (function (BABYLON) {
  55971. var AndOrNotEvaluator = /** @class */ (function () {
  55972. function AndOrNotEvaluator() {
  55973. }
  55974. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  55975. if (!query.match(/\([^\(\)]*\)/g)) {
  55976. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  55977. }
  55978. else {
  55979. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  55980. // remove parenthesis
  55981. r = r.slice(1, r.length - 1);
  55982. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  55983. });
  55984. }
  55985. if (query === "true") {
  55986. return true;
  55987. }
  55988. if (query === "false") {
  55989. return false;
  55990. }
  55991. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  55992. };
  55993. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  55994. evaluateCallback = evaluateCallback || (function (r) {
  55995. return r === "true" ? true : false;
  55996. });
  55997. var result;
  55998. var or = parenthesisContent.split("||");
  55999. for (var i in or) {
  56000. if (or.hasOwnProperty(i)) {
  56001. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  56002. var and = ori.split("&&");
  56003. if (and.length > 1) {
  56004. for (var j = 0; j < and.length; ++j) {
  56005. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  56006. if (andj !== "true" && andj !== "false") {
  56007. if (andj[0] === "!") {
  56008. result = !evaluateCallback(andj.substring(1));
  56009. }
  56010. else {
  56011. result = evaluateCallback(andj);
  56012. }
  56013. }
  56014. else {
  56015. result = andj === "true" ? true : false;
  56016. }
  56017. if (!result) {
  56018. ori = "false";
  56019. break;
  56020. }
  56021. }
  56022. }
  56023. if (result || ori === "true") {
  56024. result = true;
  56025. break;
  56026. }
  56027. // result equals false (or undefined)
  56028. if (ori !== "true" && ori !== "false") {
  56029. if (ori[0] === "!") {
  56030. result = !evaluateCallback(ori.substring(1));
  56031. }
  56032. else {
  56033. result = evaluateCallback(ori);
  56034. }
  56035. }
  56036. else {
  56037. result = ori === "true" ? true : false;
  56038. }
  56039. }
  56040. }
  56041. // the whole parenthesis scope is replaced by 'true' or 'false'
  56042. return result ? "true" : "false";
  56043. };
  56044. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  56045. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  56046. // remove whitespaces
  56047. r = r.replace(/[\s]/g, function () { return ""; });
  56048. return r.length % 2 ? "!" : "";
  56049. });
  56050. booleanString = booleanString.trim();
  56051. if (booleanString === "!true") {
  56052. booleanString = "false";
  56053. }
  56054. else if (booleanString === "!false") {
  56055. booleanString = "true";
  56056. }
  56057. return booleanString;
  56058. };
  56059. return AndOrNotEvaluator;
  56060. }());
  56061. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  56062. })(BABYLON || (BABYLON = {}));
  56063. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  56064. var BABYLON;
  56065. (function (BABYLON) {
  56066. var Database = /** @class */ (function () {
  56067. function Database(urlToScene, callbackManifestChecked) {
  56068. // Handling various flavors of prefixed version of IndexedDB
  56069. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  56070. this.callbackManifestChecked = callbackManifestChecked;
  56071. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  56072. this.db = null;
  56073. this._enableSceneOffline = false;
  56074. this._enableTexturesOffline = false;
  56075. this.manifestVersionFound = 0;
  56076. this.mustUpdateRessources = false;
  56077. this.hasReachedQuota = false;
  56078. if (!Database.IDBStorageEnabled) {
  56079. this.callbackManifestChecked(true);
  56080. }
  56081. else {
  56082. this.checkManifestFile();
  56083. }
  56084. }
  56085. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  56086. get: function () {
  56087. return this._enableSceneOffline;
  56088. },
  56089. enumerable: true,
  56090. configurable: true
  56091. });
  56092. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  56093. get: function () {
  56094. return this._enableTexturesOffline;
  56095. },
  56096. enumerable: true,
  56097. configurable: true
  56098. });
  56099. Database.prototype.checkManifestFile = function () {
  56100. var _this = this;
  56101. var noManifestFile = function () {
  56102. _this._enableSceneOffline = false;
  56103. _this._enableTexturesOffline = false;
  56104. _this.callbackManifestChecked(false);
  56105. };
  56106. var timeStampUsed = false;
  56107. var manifestURL = this.currentSceneUrl + ".manifest";
  56108. var xhr = new XMLHttpRequest();
  56109. if (navigator.onLine) {
  56110. // Adding a timestamp to by-pass browsers' cache
  56111. timeStampUsed = true;
  56112. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  56113. }
  56114. xhr.open("GET", manifestURL, true);
  56115. xhr.addEventListener("load", function () {
  56116. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  56117. try {
  56118. var manifestFile = JSON.parse(xhr.response);
  56119. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  56120. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  56121. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  56122. _this.manifestVersionFound = manifestFile.version;
  56123. }
  56124. if (_this.callbackManifestChecked) {
  56125. _this.callbackManifestChecked(true);
  56126. }
  56127. }
  56128. catch (ex) {
  56129. noManifestFile();
  56130. }
  56131. }
  56132. else {
  56133. noManifestFile();
  56134. }
  56135. }, false);
  56136. xhr.addEventListener("error", function (event) {
  56137. if (timeStampUsed) {
  56138. timeStampUsed = false;
  56139. // Let's retry without the timeStamp
  56140. // It could fail when coupled with HTML5 Offline API
  56141. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  56142. xhr.open("GET", retryManifestURL, true);
  56143. xhr.send();
  56144. }
  56145. else {
  56146. noManifestFile();
  56147. }
  56148. }, false);
  56149. try {
  56150. xhr.send();
  56151. }
  56152. catch (ex) {
  56153. BABYLON.Tools.Error("Error on XHR send request.");
  56154. this.callbackManifestChecked(false);
  56155. }
  56156. };
  56157. Database.prototype.openAsync = function (successCallback, errorCallback) {
  56158. var _this = this;
  56159. var handleError = function () {
  56160. _this.isSupported = false;
  56161. if (errorCallback)
  56162. errorCallback();
  56163. };
  56164. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  56165. // Your browser doesn't support IndexedDB
  56166. this.isSupported = false;
  56167. if (errorCallback)
  56168. errorCallback();
  56169. }
  56170. else {
  56171. // If the DB hasn't been opened or created yet
  56172. if (!this.db) {
  56173. this.hasReachedQuota = false;
  56174. this.isSupported = true;
  56175. var request = this.idbFactory.open("babylonjs", 1);
  56176. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  56177. request.onerror = function (event) {
  56178. handleError();
  56179. };
  56180. // executes when a version change transaction cannot complete due to other active transactions
  56181. request.onblocked = function (event) {
  56182. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  56183. handleError();
  56184. };
  56185. // DB has been opened successfully
  56186. request.onsuccess = function (event) {
  56187. _this.db = request.result;
  56188. successCallback();
  56189. };
  56190. // Initialization of the DB. Creating Scenes & Textures stores
  56191. request.onupgradeneeded = function (event) {
  56192. _this.db = (event.target).result;
  56193. if (_this.db) {
  56194. try {
  56195. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  56196. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  56197. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  56198. }
  56199. catch (ex) {
  56200. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  56201. handleError();
  56202. }
  56203. }
  56204. };
  56205. }
  56206. else {
  56207. if (successCallback)
  56208. successCallback();
  56209. }
  56210. }
  56211. };
  56212. Database.prototype.loadImageFromDB = function (url, image) {
  56213. var _this = this;
  56214. var completeURL = Database.ReturnFullUrlLocation(url);
  56215. var saveAndLoadImage = function () {
  56216. if (!_this.hasReachedQuota && _this.db !== null) {
  56217. // the texture is not yet in the DB, let's try to save it
  56218. _this._saveImageIntoDBAsync(completeURL, image);
  56219. }
  56220. else {
  56221. image.src = url;
  56222. }
  56223. };
  56224. if (!this.mustUpdateRessources) {
  56225. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  56226. }
  56227. else {
  56228. saveAndLoadImage();
  56229. }
  56230. };
  56231. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  56232. if (this.isSupported && this.db !== null) {
  56233. var texture;
  56234. var transaction = this.db.transaction(["textures"]);
  56235. transaction.onabort = function (event) {
  56236. image.src = url;
  56237. };
  56238. transaction.oncomplete = function (event) {
  56239. var blobTextureURL;
  56240. if (texture) {
  56241. var URL = window.URL || window.webkitURL;
  56242. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  56243. image.onerror = function () {
  56244. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  56245. image.src = url;
  56246. };
  56247. image.src = blobTextureURL;
  56248. }
  56249. else {
  56250. notInDBCallback();
  56251. }
  56252. };
  56253. var getRequest = transaction.objectStore("textures").get(url);
  56254. getRequest.onsuccess = function (event) {
  56255. texture = (event.target).result;
  56256. };
  56257. getRequest.onerror = function (event) {
  56258. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  56259. image.src = url;
  56260. };
  56261. }
  56262. else {
  56263. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56264. image.src = url;
  56265. }
  56266. };
  56267. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  56268. var _this = this;
  56269. if (this.isSupported) {
  56270. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  56271. var generateBlobUrl = function () {
  56272. var blobTextureURL;
  56273. if (blob) {
  56274. var URL = window.URL || window.webkitURL;
  56275. try {
  56276. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  56277. }
  56278. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  56279. catch (ex) {
  56280. blobTextureURL = URL.createObjectURL(blob);
  56281. }
  56282. }
  56283. if (blobTextureURL) {
  56284. image.src = blobTextureURL;
  56285. }
  56286. };
  56287. if (Database.IsUASupportingBlobStorage) {
  56288. var xhr = new XMLHttpRequest(), blob;
  56289. xhr.open("GET", url, true);
  56290. xhr.responseType = "blob";
  56291. xhr.addEventListener("load", function () {
  56292. if (xhr.status === 200 && _this.db) {
  56293. // Blob as response (XHR2)
  56294. blob = xhr.response;
  56295. var transaction = _this.db.transaction(["textures"], "readwrite");
  56296. // the transaction could abort because of a QuotaExceededError error
  56297. transaction.onabort = function (event) {
  56298. try {
  56299. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  56300. var srcElement = (event.srcElement || event.target);
  56301. var error = srcElement.error;
  56302. if (error && error.name === "QuotaExceededError") {
  56303. _this.hasReachedQuota = true;
  56304. }
  56305. }
  56306. catch (ex) { }
  56307. generateBlobUrl();
  56308. };
  56309. transaction.oncomplete = function (event) {
  56310. generateBlobUrl();
  56311. };
  56312. var newTexture = { textureUrl: url, data: blob };
  56313. try {
  56314. // Put the blob into the dabase
  56315. var addRequest = transaction.objectStore("textures").put(newTexture);
  56316. addRequest.onsuccess = function (event) {
  56317. };
  56318. addRequest.onerror = function (event) {
  56319. generateBlobUrl();
  56320. };
  56321. }
  56322. catch (ex) {
  56323. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  56324. if (ex.code === 25) {
  56325. Database.IsUASupportingBlobStorage = false;
  56326. }
  56327. image.src = url;
  56328. }
  56329. }
  56330. else {
  56331. image.src = url;
  56332. }
  56333. }, false);
  56334. xhr.addEventListener("error", function (event) {
  56335. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  56336. image.src = url;
  56337. }, false);
  56338. xhr.send();
  56339. }
  56340. else {
  56341. image.src = url;
  56342. }
  56343. }
  56344. else {
  56345. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56346. image.src = url;
  56347. }
  56348. };
  56349. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  56350. var _this = this;
  56351. var updateVersion = function () {
  56352. // the version is not yet in the DB or we need to update it
  56353. _this._saveVersionIntoDBAsync(url, versionLoaded);
  56354. };
  56355. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  56356. };
  56357. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  56358. var _this = this;
  56359. if (this.isSupported && this.db) {
  56360. var version;
  56361. try {
  56362. var transaction = this.db.transaction(["versions"]);
  56363. transaction.oncomplete = function (event) {
  56364. if (version) {
  56365. // If the version in the JSON file is > than the version in DB
  56366. if (_this.manifestVersionFound > version.data) {
  56367. _this.mustUpdateRessources = true;
  56368. updateInDBCallback();
  56369. }
  56370. else {
  56371. callback(version.data);
  56372. }
  56373. }
  56374. else {
  56375. _this.mustUpdateRessources = true;
  56376. updateInDBCallback();
  56377. }
  56378. };
  56379. transaction.onabort = function (event) {
  56380. callback(-1);
  56381. };
  56382. var getRequest = transaction.objectStore("versions").get(url);
  56383. getRequest.onsuccess = function (event) {
  56384. version = (event.target).result;
  56385. };
  56386. getRequest.onerror = function (event) {
  56387. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  56388. callback(-1);
  56389. };
  56390. }
  56391. catch (ex) {
  56392. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  56393. callback(-1);
  56394. }
  56395. }
  56396. else {
  56397. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56398. callback(-1);
  56399. }
  56400. };
  56401. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  56402. var _this = this;
  56403. if (this.isSupported && !this.hasReachedQuota && this.db) {
  56404. try {
  56405. // Open a transaction to the database
  56406. var transaction = this.db.transaction(["versions"], "readwrite");
  56407. // the transaction could abort because of a QuotaExceededError error
  56408. transaction.onabort = function (event) {
  56409. try {
  56410. var error = event.srcElement['error'];
  56411. if (error && error.name === "QuotaExceededError") {
  56412. _this.hasReachedQuota = true;
  56413. }
  56414. }
  56415. catch (ex) { }
  56416. callback(-1);
  56417. };
  56418. transaction.oncomplete = function (event) {
  56419. callback(_this.manifestVersionFound);
  56420. };
  56421. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  56422. // Put the scene into the database
  56423. var addRequest = transaction.objectStore("versions").put(newVersion);
  56424. addRequest.onsuccess = function (event) {
  56425. };
  56426. addRequest.onerror = function (event) {
  56427. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  56428. };
  56429. }
  56430. catch (ex) {
  56431. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  56432. callback(-1);
  56433. }
  56434. }
  56435. else {
  56436. callback(-1);
  56437. }
  56438. };
  56439. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  56440. var _this = this;
  56441. var completeUrl = Database.ReturnFullUrlLocation(url);
  56442. var saveAndLoadFile = function () {
  56443. // the scene is not yet in the DB, let's try to save it
  56444. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  56445. };
  56446. this._checkVersionFromDB(completeUrl, function (version) {
  56447. if (version !== -1) {
  56448. if (!_this.mustUpdateRessources) {
  56449. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  56450. }
  56451. else {
  56452. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  56453. }
  56454. }
  56455. else {
  56456. if (errorCallback) {
  56457. errorCallback();
  56458. }
  56459. }
  56460. });
  56461. };
  56462. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  56463. if (this.isSupported && this.db) {
  56464. var targetStore;
  56465. if (url.indexOf(".babylon") !== -1) {
  56466. targetStore = "scenes";
  56467. }
  56468. else {
  56469. targetStore = "textures";
  56470. }
  56471. var file;
  56472. var transaction = this.db.transaction([targetStore]);
  56473. transaction.oncomplete = function (event) {
  56474. if (file) {
  56475. callback(file.data);
  56476. }
  56477. else {
  56478. notInDBCallback();
  56479. }
  56480. };
  56481. transaction.onabort = function (event) {
  56482. notInDBCallback();
  56483. };
  56484. var getRequest = transaction.objectStore(targetStore).get(url);
  56485. getRequest.onsuccess = function (event) {
  56486. file = (event.target).result;
  56487. };
  56488. getRequest.onerror = function (event) {
  56489. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  56490. notInDBCallback();
  56491. };
  56492. }
  56493. else {
  56494. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56495. callback();
  56496. }
  56497. };
  56498. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  56499. var _this = this;
  56500. if (this.isSupported) {
  56501. var targetStore;
  56502. if (url.indexOf(".babylon") !== -1) {
  56503. targetStore = "scenes";
  56504. }
  56505. else {
  56506. targetStore = "textures";
  56507. }
  56508. // Create XHR
  56509. var xhr = new XMLHttpRequest();
  56510. var fileData;
  56511. xhr.open("GET", url, true);
  56512. if (useArrayBuffer) {
  56513. xhr.responseType = "arraybuffer";
  56514. }
  56515. if (progressCallback) {
  56516. xhr.onprogress = progressCallback;
  56517. }
  56518. xhr.addEventListener("load", function () {
  56519. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  56520. // Blob as response (XHR2)
  56521. //fileData = xhr.responseText;
  56522. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  56523. if (!_this.hasReachedQuota && _this.db) {
  56524. // Open a transaction to the database
  56525. var transaction = _this.db.transaction([targetStore], "readwrite");
  56526. // the transaction could abort because of a QuotaExceededError error
  56527. transaction.onabort = function (event) {
  56528. try {
  56529. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  56530. var error = event.srcElement['error'];
  56531. if (error && error.name === "QuotaExceededError") {
  56532. _this.hasReachedQuota = true;
  56533. }
  56534. }
  56535. catch (ex) { }
  56536. callback(fileData);
  56537. };
  56538. transaction.oncomplete = function (event) {
  56539. callback(fileData);
  56540. };
  56541. var newFile;
  56542. if (targetStore === "scenes") {
  56543. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  56544. }
  56545. else {
  56546. newFile = { textureUrl: url, data: fileData };
  56547. }
  56548. try {
  56549. // Put the scene into the database
  56550. var addRequest = transaction.objectStore(targetStore).put(newFile);
  56551. addRequest.onsuccess = function (event) {
  56552. };
  56553. addRequest.onerror = function (event) {
  56554. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  56555. };
  56556. }
  56557. catch (ex) {
  56558. callback(fileData);
  56559. }
  56560. }
  56561. else {
  56562. callback(fileData);
  56563. }
  56564. }
  56565. else {
  56566. callback();
  56567. }
  56568. }, false);
  56569. xhr.addEventListener("error", function (event) {
  56570. BABYLON.Tools.Error("error on XHR request.");
  56571. callback();
  56572. }, false);
  56573. xhr.send();
  56574. }
  56575. else {
  56576. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56577. callback();
  56578. }
  56579. };
  56580. Database.IsUASupportingBlobStorage = true;
  56581. Database.IDBStorageEnabled = true;
  56582. Database.parseURL = function (url) {
  56583. var a = document.createElement('a');
  56584. a.href = url;
  56585. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  56586. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  56587. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  56588. return absLocation;
  56589. };
  56590. Database.ReturnFullUrlLocation = function (url) {
  56591. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  56592. return (Database.parseURL(window.location.href) + url);
  56593. }
  56594. else {
  56595. return url;
  56596. }
  56597. };
  56598. return Database;
  56599. }());
  56600. BABYLON.Database = Database;
  56601. })(BABYLON || (BABYLON = {}));
  56602. //# sourceMappingURL=babylon.database.js.map
  56603. var BABYLON;
  56604. (function (BABYLON) {
  56605. var FresnelParameters = /** @class */ (function () {
  56606. function FresnelParameters() {
  56607. this._isEnabled = true;
  56608. this.leftColor = BABYLON.Color3.White();
  56609. this.rightColor = BABYLON.Color3.Black();
  56610. this.bias = 0;
  56611. this.power = 1;
  56612. }
  56613. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  56614. get: function () {
  56615. return this._isEnabled;
  56616. },
  56617. set: function (value) {
  56618. if (this._isEnabled === value) {
  56619. return;
  56620. }
  56621. this._isEnabled = value;
  56622. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  56623. },
  56624. enumerable: true,
  56625. configurable: true
  56626. });
  56627. FresnelParameters.prototype.clone = function () {
  56628. var newFresnelParameters = new FresnelParameters();
  56629. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  56630. return newFresnelParameters;
  56631. };
  56632. FresnelParameters.prototype.serialize = function () {
  56633. var serializationObject = {};
  56634. serializationObject.isEnabled = this.isEnabled;
  56635. serializationObject.leftColor = this.leftColor;
  56636. serializationObject.rightColor = this.rightColor;
  56637. serializationObject.bias = this.bias;
  56638. serializationObject.power = this.power;
  56639. return serializationObject;
  56640. };
  56641. FresnelParameters.Parse = function (parsedFresnelParameters) {
  56642. var fresnelParameters = new FresnelParameters();
  56643. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  56644. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  56645. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  56646. fresnelParameters.bias = parsedFresnelParameters.bias;
  56647. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  56648. return fresnelParameters;
  56649. };
  56650. return FresnelParameters;
  56651. }());
  56652. BABYLON.FresnelParameters = FresnelParameters;
  56653. })(BABYLON || (BABYLON = {}));
  56654. //# sourceMappingURL=babylon.fresnelParameters.js.map
  56655. var BABYLON;
  56656. (function (BABYLON) {
  56657. var MultiMaterial = /** @class */ (function (_super) {
  56658. __extends(MultiMaterial, _super);
  56659. function MultiMaterial(name, scene) {
  56660. var _this = _super.call(this, name, scene, true) || this;
  56661. scene.multiMaterials.push(_this);
  56662. _this.subMaterials = new Array();
  56663. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  56664. return _this;
  56665. }
  56666. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  56667. get: function () {
  56668. return this._subMaterials;
  56669. },
  56670. set: function (value) {
  56671. this._subMaterials = value;
  56672. this._hookArray(value);
  56673. },
  56674. enumerable: true,
  56675. configurable: true
  56676. });
  56677. MultiMaterial.prototype._hookArray = function (array) {
  56678. var _this = this;
  56679. var oldPush = array.push;
  56680. array.push = function () {
  56681. var items = [];
  56682. for (var _i = 0; _i < arguments.length; _i++) {
  56683. items[_i] = arguments[_i];
  56684. }
  56685. var result = oldPush.apply(array, items);
  56686. _this._markAllSubMeshesAsTexturesDirty();
  56687. return result;
  56688. };
  56689. var oldSplice = array.splice;
  56690. array.splice = function (index, deleteCount) {
  56691. var deleted = oldSplice.apply(array, [index, deleteCount]);
  56692. _this._markAllSubMeshesAsTexturesDirty();
  56693. return deleted;
  56694. };
  56695. };
  56696. // Properties
  56697. MultiMaterial.prototype.getSubMaterial = function (index) {
  56698. if (index < 0 || index >= this.subMaterials.length) {
  56699. return this.getScene().defaultMaterial;
  56700. }
  56701. return this.subMaterials[index];
  56702. };
  56703. MultiMaterial.prototype.getActiveTextures = function () {
  56704. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  56705. if (subMaterial) {
  56706. return subMaterial.getActiveTextures();
  56707. }
  56708. else {
  56709. return [];
  56710. }
  56711. }));
  56712. var _a;
  56713. };
  56714. // Methods
  56715. MultiMaterial.prototype.getClassName = function () {
  56716. return "MultiMaterial";
  56717. };
  56718. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  56719. for (var index = 0; index < this.subMaterials.length; index++) {
  56720. var subMaterial = this.subMaterials[index];
  56721. if (subMaterial) {
  56722. if (subMaterial.storeEffectOnSubMeshes) {
  56723. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  56724. return false;
  56725. }
  56726. continue;
  56727. }
  56728. if (!subMaterial.isReady(mesh)) {
  56729. return false;
  56730. }
  56731. }
  56732. }
  56733. return true;
  56734. };
  56735. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  56736. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  56737. for (var index = 0; index < this.subMaterials.length; index++) {
  56738. var subMaterial = null;
  56739. var current = this.subMaterials[index];
  56740. if (cloneChildren && current) {
  56741. subMaterial = current.clone(name + "-" + current.name);
  56742. }
  56743. else {
  56744. subMaterial = this.subMaterials[index];
  56745. }
  56746. newMultiMaterial.subMaterials.push(subMaterial);
  56747. }
  56748. return newMultiMaterial;
  56749. };
  56750. MultiMaterial.prototype.serialize = function () {
  56751. var serializationObject = {};
  56752. serializationObject.name = this.name;
  56753. serializationObject.id = this.id;
  56754. if (BABYLON.Tags) {
  56755. serializationObject.tags = BABYLON.Tags.GetTags(this);
  56756. }
  56757. serializationObject.materials = [];
  56758. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  56759. var subMat = this.subMaterials[matIndex];
  56760. if (subMat) {
  56761. serializationObject.materials.push(subMat.id);
  56762. }
  56763. else {
  56764. serializationObject.materials.push(null);
  56765. }
  56766. }
  56767. return serializationObject;
  56768. };
  56769. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  56770. var scene = this.getScene();
  56771. if (!scene) {
  56772. return;
  56773. }
  56774. var index = scene.multiMaterials.indexOf(this);
  56775. if (index >= 0) {
  56776. scene.multiMaterials.splice(index, 1);
  56777. }
  56778. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  56779. };
  56780. return MultiMaterial;
  56781. }(BABYLON.Material));
  56782. BABYLON.MultiMaterial = MultiMaterial;
  56783. })(BABYLON || (BABYLON = {}));
  56784. //# sourceMappingURL=babylon.multiMaterial.js.map
  56785. var BABYLON;
  56786. (function (BABYLON) {
  56787. var FreeCameraTouchInput = /** @class */ (function () {
  56788. function FreeCameraTouchInput() {
  56789. this._offsetX = null;
  56790. this._offsetY = null;
  56791. this._pointerPressed = new Array();
  56792. this.touchAngularSensibility = 200000.0;
  56793. this.touchMoveSensibility = 250.0;
  56794. }
  56795. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  56796. var _this = this;
  56797. var previousPosition = null;
  56798. if (this._pointerInput === undefined) {
  56799. this._onLostFocus = function (evt) {
  56800. _this._offsetX = null;
  56801. _this._offsetY = null;
  56802. };
  56803. this._pointerInput = function (p, s) {
  56804. var evt = p.event;
  56805. if (evt.pointerType === "mouse") {
  56806. return;
  56807. }
  56808. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  56809. if (!noPreventDefault) {
  56810. evt.preventDefault();
  56811. }
  56812. _this._pointerPressed.push(evt.pointerId);
  56813. if (_this._pointerPressed.length !== 1) {
  56814. return;
  56815. }
  56816. previousPosition = {
  56817. x: evt.clientX,
  56818. y: evt.clientY
  56819. };
  56820. }
  56821. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  56822. if (!noPreventDefault) {
  56823. evt.preventDefault();
  56824. }
  56825. var index = _this._pointerPressed.indexOf(evt.pointerId);
  56826. if (index === -1) {
  56827. return;
  56828. }
  56829. _this._pointerPressed.splice(index, 1);
  56830. if (index != 0) {
  56831. return;
  56832. }
  56833. previousPosition = null;
  56834. _this._offsetX = null;
  56835. _this._offsetY = null;
  56836. }
  56837. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  56838. if (!noPreventDefault) {
  56839. evt.preventDefault();
  56840. }
  56841. if (!previousPosition) {
  56842. return;
  56843. }
  56844. var index = _this._pointerPressed.indexOf(evt.pointerId);
  56845. if (index != 0) {
  56846. return;
  56847. }
  56848. _this._offsetX = evt.clientX - previousPosition.x;
  56849. _this._offsetY = -(evt.clientY - previousPosition.y);
  56850. }
  56851. };
  56852. }
  56853. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  56854. if (this._onLostFocus) {
  56855. element.addEventListener("blur", this._onLostFocus);
  56856. }
  56857. };
  56858. FreeCameraTouchInput.prototype.detachControl = function (element) {
  56859. if (this._pointerInput && element) {
  56860. if (this._observer) {
  56861. this.camera.getScene().onPointerObservable.remove(this._observer);
  56862. this._observer = null;
  56863. }
  56864. if (this._onLostFocus) {
  56865. element.removeEventListener("blur", this._onLostFocus);
  56866. this._onLostFocus = null;
  56867. }
  56868. this._pointerPressed = [];
  56869. this._offsetX = null;
  56870. this._offsetY = null;
  56871. }
  56872. };
  56873. FreeCameraTouchInput.prototype.checkInputs = function () {
  56874. if (this._offsetX && this._offsetY) {
  56875. var camera = this.camera;
  56876. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  56877. if (this._pointerPressed.length > 1) {
  56878. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  56879. }
  56880. else {
  56881. var speed = camera._computeLocalCameraSpeed();
  56882. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  56883. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  56884. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  56885. }
  56886. }
  56887. };
  56888. FreeCameraTouchInput.prototype.getClassName = function () {
  56889. return "FreeCameraTouchInput";
  56890. };
  56891. FreeCameraTouchInput.prototype.getSimpleName = function () {
  56892. return "touch";
  56893. };
  56894. __decorate([
  56895. BABYLON.serialize()
  56896. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  56897. __decorate([
  56898. BABYLON.serialize()
  56899. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  56900. return FreeCameraTouchInput;
  56901. }());
  56902. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  56903. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  56904. })(BABYLON || (BABYLON = {}));
  56905. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  56906. var BABYLON;
  56907. (function (BABYLON) {
  56908. // We're mainly based on the logic defined into the FreeCamera code
  56909. var TouchCamera = /** @class */ (function (_super) {
  56910. __extends(TouchCamera, _super);
  56911. //-- end properties for backward compatibility for inputs
  56912. function TouchCamera(name, position, scene) {
  56913. var _this = _super.call(this, name, position, scene) || this;
  56914. _this.inputs.addTouch();
  56915. _this._setupInputs();
  56916. return _this;
  56917. }
  56918. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  56919. //-- Begin properties for backward compatibility for inputs
  56920. get: function () {
  56921. var touch = this.inputs.attached["touch"];
  56922. if (touch)
  56923. return touch.touchAngularSensibility;
  56924. return 0;
  56925. },
  56926. set: function (value) {
  56927. var touch = this.inputs.attached["touch"];
  56928. if (touch)
  56929. touch.touchAngularSensibility = value;
  56930. },
  56931. enumerable: true,
  56932. configurable: true
  56933. });
  56934. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  56935. get: function () {
  56936. var touch = this.inputs.attached["touch"];
  56937. if (touch)
  56938. return touch.touchMoveSensibility;
  56939. return 0;
  56940. },
  56941. set: function (value) {
  56942. var touch = this.inputs.attached["touch"];
  56943. if (touch)
  56944. touch.touchMoveSensibility = value;
  56945. },
  56946. enumerable: true,
  56947. configurable: true
  56948. });
  56949. TouchCamera.prototype.getClassName = function () {
  56950. return "TouchCamera";
  56951. };
  56952. TouchCamera.prototype._setupInputs = function () {
  56953. var mouse = this.inputs.attached["mouse"];
  56954. if (mouse) {
  56955. mouse.touchEnabled = false;
  56956. }
  56957. };
  56958. return TouchCamera;
  56959. }(BABYLON.FreeCamera));
  56960. BABYLON.TouchCamera = TouchCamera;
  56961. })(BABYLON || (BABYLON = {}));
  56962. //# sourceMappingURL=babylon.touchCamera.js.map
  56963. var BABYLON;
  56964. (function (BABYLON) {
  56965. var ProceduralTexture = /** @class */ (function (_super) {
  56966. __extends(ProceduralTexture, _super);
  56967. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  56968. if (fallbackTexture === void 0) { fallbackTexture = null; }
  56969. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56970. if (isCube === void 0) { isCube = false; }
  56971. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  56972. _this.isCube = isCube;
  56973. _this.isEnabled = true;
  56974. _this._currentRefreshId = -1;
  56975. _this._refreshRate = 1;
  56976. _this._vertexBuffers = {};
  56977. _this._uniforms = new Array();
  56978. _this._samplers = new Array();
  56979. _this._textures = {};
  56980. _this._floats = {};
  56981. _this._floatsArrays = {};
  56982. _this._colors3 = {};
  56983. _this._colors4 = {};
  56984. _this._vectors2 = {};
  56985. _this._vectors3 = {};
  56986. _this._matrices = {};
  56987. _this._fallbackTextureUsed = false;
  56988. scene._proceduralTextures.push(_this);
  56989. _this._engine = scene.getEngine();
  56990. _this.name = name;
  56991. _this.isRenderTarget = true;
  56992. _this._size = size;
  56993. _this._generateMipMaps = generateMipMaps;
  56994. _this.setFragment(fragment);
  56995. _this._fallbackTexture = fallbackTexture;
  56996. if (isCube) {
  56997. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  56998. _this.setFloat("face", 0);
  56999. }
  57000. else {
  57001. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  57002. }
  57003. // VBO
  57004. var vertices = [];
  57005. vertices.push(1, 1);
  57006. vertices.push(-1, 1);
  57007. vertices.push(-1, -1);
  57008. vertices.push(1, -1);
  57009. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  57010. _this._createIndexBuffer();
  57011. return _this;
  57012. }
  57013. ProceduralTexture.prototype._createIndexBuffer = function () {
  57014. var engine = this._engine;
  57015. // Indices
  57016. var indices = [];
  57017. indices.push(0);
  57018. indices.push(1);
  57019. indices.push(2);
  57020. indices.push(0);
  57021. indices.push(2);
  57022. indices.push(3);
  57023. this._indexBuffer = engine.createIndexBuffer(indices);
  57024. };
  57025. ProceduralTexture.prototype._rebuild = function () {
  57026. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  57027. if (vb) {
  57028. vb._rebuild();
  57029. }
  57030. this._createIndexBuffer();
  57031. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  57032. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  57033. }
  57034. };
  57035. ProceduralTexture.prototype.reset = function () {
  57036. if (this._effect === undefined) {
  57037. return;
  57038. }
  57039. var engine = this._engine;
  57040. engine._releaseEffect(this._effect);
  57041. };
  57042. ProceduralTexture.prototype.isReady = function () {
  57043. var _this = this;
  57044. var engine = this._engine;
  57045. var shaders;
  57046. if (!this._fragment) {
  57047. return false;
  57048. }
  57049. if (this._fallbackTextureUsed) {
  57050. return true;
  57051. }
  57052. if (this._fragment.fragmentElement !== undefined) {
  57053. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  57054. }
  57055. else {
  57056. shaders = { vertex: "procedural", fragment: this._fragment };
  57057. }
  57058. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  57059. _this.releaseInternalTexture();
  57060. if (_this._fallbackTexture) {
  57061. _this._texture = _this._fallbackTexture._texture;
  57062. if (_this._texture) {
  57063. _this._texture.incrementReferences();
  57064. }
  57065. }
  57066. _this._fallbackTextureUsed = true;
  57067. });
  57068. return this._effect.isReady();
  57069. };
  57070. ProceduralTexture.prototype.resetRefreshCounter = function () {
  57071. this._currentRefreshId = -1;
  57072. };
  57073. ProceduralTexture.prototype.setFragment = function (fragment) {
  57074. this._fragment = fragment;
  57075. };
  57076. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  57077. get: function () {
  57078. return this._refreshRate;
  57079. },
  57080. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57081. set: function (value) {
  57082. this._refreshRate = value;
  57083. this.resetRefreshCounter();
  57084. },
  57085. enumerable: true,
  57086. configurable: true
  57087. });
  57088. ProceduralTexture.prototype._shouldRender = function () {
  57089. if (!this.isEnabled || !this.isReady() || !this._texture) {
  57090. return false;
  57091. }
  57092. if (this._fallbackTextureUsed) {
  57093. return false;
  57094. }
  57095. if (this._currentRefreshId === -1) {
  57096. this._currentRefreshId = 1;
  57097. return true;
  57098. }
  57099. if (this.refreshRate === this._currentRefreshId) {
  57100. this._currentRefreshId = 1;
  57101. return true;
  57102. }
  57103. this._currentRefreshId++;
  57104. return false;
  57105. };
  57106. ProceduralTexture.prototype.getRenderSize = function () {
  57107. return this._size;
  57108. };
  57109. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  57110. if (this._fallbackTextureUsed) {
  57111. return;
  57112. }
  57113. this.releaseInternalTexture();
  57114. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  57115. };
  57116. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  57117. if (this._uniforms.indexOf(uniformName) === -1) {
  57118. this._uniforms.push(uniformName);
  57119. }
  57120. };
  57121. ProceduralTexture.prototype.setTexture = function (name, texture) {
  57122. if (this._samplers.indexOf(name) === -1) {
  57123. this._samplers.push(name);
  57124. }
  57125. this._textures[name] = texture;
  57126. return this;
  57127. };
  57128. ProceduralTexture.prototype.setFloat = function (name, value) {
  57129. this._checkUniform(name);
  57130. this._floats[name] = value;
  57131. return this;
  57132. };
  57133. ProceduralTexture.prototype.setFloats = function (name, value) {
  57134. this._checkUniform(name);
  57135. this._floatsArrays[name] = value;
  57136. return this;
  57137. };
  57138. ProceduralTexture.prototype.setColor3 = function (name, value) {
  57139. this._checkUniform(name);
  57140. this._colors3[name] = value;
  57141. return this;
  57142. };
  57143. ProceduralTexture.prototype.setColor4 = function (name, value) {
  57144. this._checkUniform(name);
  57145. this._colors4[name] = value;
  57146. return this;
  57147. };
  57148. ProceduralTexture.prototype.setVector2 = function (name, value) {
  57149. this._checkUniform(name);
  57150. this._vectors2[name] = value;
  57151. return this;
  57152. };
  57153. ProceduralTexture.prototype.setVector3 = function (name, value) {
  57154. this._checkUniform(name);
  57155. this._vectors3[name] = value;
  57156. return this;
  57157. };
  57158. ProceduralTexture.prototype.setMatrix = function (name, value) {
  57159. this._checkUniform(name);
  57160. this._matrices[name] = value;
  57161. return this;
  57162. };
  57163. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  57164. var scene = this.getScene();
  57165. if (!scene) {
  57166. return;
  57167. }
  57168. var engine = this._engine;
  57169. // Render
  57170. engine.enableEffect(this._effect);
  57171. engine.setState(false);
  57172. // Texture
  57173. for (var name in this._textures) {
  57174. this._effect.setTexture(name, this._textures[name]);
  57175. }
  57176. // Float
  57177. for (name in this._floats) {
  57178. this._effect.setFloat(name, this._floats[name]);
  57179. }
  57180. // Floats
  57181. for (name in this._floatsArrays) {
  57182. this._effect.setArray(name, this._floatsArrays[name]);
  57183. }
  57184. // Color3
  57185. for (name in this._colors3) {
  57186. this._effect.setColor3(name, this._colors3[name]);
  57187. }
  57188. // Color4
  57189. for (name in this._colors4) {
  57190. var color = this._colors4[name];
  57191. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  57192. }
  57193. // Vector2
  57194. for (name in this._vectors2) {
  57195. this._effect.setVector2(name, this._vectors2[name]);
  57196. }
  57197. // Vector3
  57198. for (name in this._vectors3) {
  57199. this._effect.setVector3(name, this._vectors3[name]);
  57200. }
  57201. // Matrix
  57202. for (name in this._matrices) {
  57203. this._effect.setMatrix(name, this._matrices[name]);
  57204. }
  57205. if (!this._texture) {
  57206. return;
  57207. }
  57208. if (this.isCube) {
  57209. for (var face = 0; face < 6; face++) {
  57210. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  57211. // VBOs
  57212. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  57213. this._effect.setFloat("face", face);
  57214. // Clear
  57215. engine.clear(scene.clearColor, true, true, true);
  57216. // Draw order
  57217. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  57218. // Mipmaps
  57219. if (face === 5) {
  57220. engine.generateMipMapsForCubemap(this._texture);
  57221. }
  57222. }
  57223. }
  57224. else {
  57225. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  57226. // VBOs
  57227. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  57228. // Clear
  57229. engine.clear(scene.clearColor, true, true, true);
  57230. // Draw order
  57231. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  57232. }
  57233. // Unbind
  57234. engine.unBindFramebuffer(this._texture, this.isCube);
  57235. if (this.onGenerated) {
  57236. this.onGenerated();
  57237. }
  57238. };
  57239. ProceduralTexture.prototype.clone = function () {
  57240. var textureSize = this.getSize();
  57241. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  57242. // Base texture
  57243. newTexture.hasAlpha = this.hasAlpha;
  57244. newTexture.level = this.level;
  57245. // RenderTarget Texture
  57246. newTexture.coordinatesMode = this.coordinatesMode;
  57247. return newTexture;
  57248. };
  57249. ProceduralTexture.prototype.dispose = function () {
  57250. var scene = this.getScene();
  57251. if (!scene) {
  57252. return;
  57253. }
  57254. var index = scene._proceduralTextures.indexOf(this);
  57255. if (index >= 0) {
  57256. scene._proceduralTextures.splice(index, 1);
  57257. }
  57258. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  57259. if (vertexBuffer) {
  57260. vertexBuffer.dispose();
  57261. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  57262. }
  57263. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  57264. this._indexBuffer = null;
  57265. }
  57266. _super.prototype.dispose.call(this);
  57267. };
  57268. return ProceduralTexture;
  57269. }(BABYLON.Texture));
  57270. BABYLON.ProceduralTexture = ProceduralTexture;
  57271. })(BABYLON || (BABYLON = {}));
  57272. //# sourceMappingURL=babylon.proceduralTexture.js.map
  57273. var BABYLON;
  57274. (function (BABYLON) {
  57275. var CustomProceduralTexture = /** @class */ (function (_super) {
  57276. __extends(CustomProceduralTexture, _super);
  57277. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  57278. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  57279. _this._animate = true;
  57280. _this._time = 0;
  57281. _this._texturePath = texturePath;
  57282. //Try to load json
  57283. _this.loadJson(texturePath);
  57284. _this.refreshRate = 1;
  57285. return _this;
  57286. }
  57287. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  57288. var _this = this;
  57289. var noConfigFile = function () {
  57290. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  57291. try {
  57292. _this.setFragment(_this._texturePath);
  57293. }
  57294. catch (ex) {
  57295. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  57296. }
  57297. };
  57298. var configFileUrl = jsonUrl + "/config.json";
  57299. var xhr = new XMLHttpRequest();
  57300. xhr.open("GET", configFileUrl, true);
  57301. xhr.addEventListener("load", function () {
  57302. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  57303. try {
  57304. _this._config = JSON.parse(xhr.response);
  57305. _this.updateShaderUniforms();
  57306. _this.updateTextures();
  57307. _this.setFragment(_this._texturePath + "/custom");
  57308. _this._animate = _this._config.animate;
  57309. _this.refreshRate = _this._config.refreshrate;
  57310. }
  57311. catch (ex) {
  57312. noConfigFile();
  57313. }
  57314. }
  57315. else {
  57316. noConfigFile();
  57317. }
  57318. }, false);
  57319. xhr.addEventListener("error", function () {
  57320. noConfigFile();
  57321. }, false);
  57322. try {
  57323. xhr.send();
  57324. }
  57325. catch (ex) {
  57326. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  57327. }
  57328. };
  57329. CustomProceduralTexture.prototype.isReady = function () {
  57330. if (!_super.prototype.isReady.call(this)) {
  57331. return false;
  57332. }
  57333. for (var name in this._textures) {
  57334. var texture = this._textures[name];
  57335. if (!texture.isReady()) {
  57336. return false;
  57337. }
  57338. }
  57339. return true;
  57340. };
  57341. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  57342. var scene = this.getScene();
  57343. if (this._animate && scene) {
  57344. this._time += scene.getAnimationRatio() * 0.03;
  57345. this.updateShaderUniforms();
  57346. }
  57347. _super.prototype.render.call(this, useCameraPostProcess);
  57348. };
  57349. CustomProceduralTexture.prototype.updateTextures = function () {
  57350. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  57351. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  57352. }
  57353. };
  57354. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  57355. if (this._config) {
  57356. for (var j = 0; j < this._config.uniforms.length; j++) {
  57357. var uniform = this._config.uniforms[j];
  57358. switch (uniform.type) {
  57359. case "float":
  57360. this.setFloat(uniform.name, uniform.value);
  57361. break;
  57362. case "color3":
  57363. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  57364. break;
  57365. case "color4":
  57366. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  57367. break;
  57368. case "vector2":
  57369. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  57370. break;
  57371. case "vector3":
  57372. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  57373. break;
  57374. }
  57375. }
  57376. }
  57377. this.setFloat("time", this._time);
  57378. };
  57379. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  57380. get: function () {
  57381. return this._animate;
  57382. },
  57383. set: function (value) {
  57384. this._animate = value;
  57385. },
  57386. enumerable: true,
  57387. configurable: true
  57388. });
  57389. return CustomProceduralTexture;
  57390. }(BABYLON.ProceduralTexture));
  57391. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  57392. })(BABYLON || (BABYLON = {}));
  57393. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  57394. var BABYLON;
  57395. (function (BABYLON) {
  57396. var FreeCameraGamepadInput = /** @class */ (function () {
  57397. function FreeCameraGamepadInput() {
  57398. this.gamepadAngularSensibility = 200;
  57399. this.gamepadMoveSensibility = 40;
  57400. // private members
  57401. this._cameraTransform = BABYLON.Matrix.Identity();
  57402. this._deltaTransform = BABYLON.Vector3.Zero();
  57403. this._vector3 = BABYLON.Vector3.Zero();
  57404. this._vector2 = BABYLON.Vector2.Zero();
  57405. }
  57406. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  57407. var _this = this;
  57408. var manager = this.camera.getScene().gamepadManager;
  57409. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  57410. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  57411. // prioritize XBOX gamepads.
  57412. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  57413. _this.gamepad = gamepad;
  57414. }
  57415. }
  57416. });
  57417. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  57418. if (_this.gamepad === gamepad) {
  57419. _this.gamepad = null;
  57420. }
  57421. });
  57422. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  57423. };
  57424. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  57425. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  57426. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  57427. this.gamepad = null;
  57428. };
  57429. FreeCameraGamepadInput.prototype.checkInputs = function () {
  57430. if (this.gamepad && this.gamepad.leftStick) {
  57431. var camera = this.camera;
  57432. var LSValues = this.gamepad.leftStick;
  57433. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  57434. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  57435. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  57436. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  57437. var RSValues = this.gamepad.rightStick;
  57438. if (RSValues) {
  57439. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  57440. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  57441. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  57442. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  57443. }
  57444. else {
  57445. RSValues = { x: 0, y: 0 };
  57446. }
  57447. if (!camera.rotationQuaternion) {
  57448. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  57449. }
  57450. else {
  57451. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  57452. }
  57453. var speed = camera._computeLocalCameraSpeed() * 50.0;
  57454. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  57455. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  57456. camera.cameraDirection.addInPlace(this._deltaTransform);
  57457. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  57458. camera.cameraRotation.addInPlace(this._vector2);
  57459. }
  57460. };
  57461. FreeCameraGamepadInput.prototype.getClassName = function () {
  57462. return "FreeCameraGamepadInput";
  57463. };
  57464. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  57465. return "gamepad";
  57466. };
  57467. __decorate([
  57468. BABYLON.serialize()
  57469. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  57470. __decorate([
  57471. BABYLON.serialize()
  57472. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  57473. return FreeCameraGamepadInput;
  57474. }());
  57475. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  57476. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  57477. })(BABYLON || (BABYLON = {}));
  57478. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  57479. var BABYLON;
  57480. (function (BABYLON) {
  57481. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  57482. function ArcRotateCameraGamepadInput() {
  57483. this.gamepadRotationSensibility = 80;
  57484. this.gamepadMoveSensibility = 40;
  57485. }
  57486. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  57487. var _this = this;
  57488. var manager = this.camera.getScene().gamepadManager;
  57489. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  57490. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  57491. // prioritize XBOX gamepads.
  57492. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  57493. _this.gamepad = gamepad;
  57494. }
  57495. }
  57496. });
  57497. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  57498. if (_this.gamepad === gamepad) {
  57499. _this.gamepad = null;
  57500. }
  57501. });
  57502. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  57503. };
  57504. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  57505. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  57506. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  57507. this.gamepad = null;
  57508. };
  57509. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  57510. if (this.gamepad) {
  57511. var camera = this.camera;
  57512. var RSValues = this.gamepad.rightStick;
  57513. if (RSValues) {
  57514. if (RSValues.x != 0) {
  57515. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  57516. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  57517. camera.inertialAlphaOffset += normalizedRX;
  57518. }
  57519. }
  57520. if (RSValues.y != 0) {
  57521. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  57522. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  57523. camera.inertialBetaOffset += normalizedRY;
  57524. }
  57525. }
  57526. }
  57527. var LSValues = this.gamepad.leftStick;
  57528. if (LSValues && LSValues.y != 0) {
  57529. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  57530. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  57531. this.camera.inertialRadiusOffset -= normalizedLY;
  57532. }
  57533. }
  57534. }
  57535. };
  57536. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  57537. return "ArcRotateCameraGamepadInput";
  57538. };
  57539. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  57540. return "gamepad";
  57541. };
  57542. __decorate([
  57543. BABYLON.serialize()
  57544. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  57545. __decorate([
  57546. BABYLON.serialize()
  57547. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  57548. return ArcRotateCameraGamepadInput;
  57549. }());
  57550. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  57551. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  57552. })(BABYLON || (BABYLON = {}));
  57553. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  57554. var BABYLON;
  57555. (function (BABYLON) {
  57556. var GamepadManager = /** @class */ (function () {
  57557. function GamepadManager(_scene) {
  57558. var _this = this;
  57559. this._scene = _scene;
  57560. this._babylonGamepads = [];
  57561. this._oneGamepadConnected = false;
  57562. this._isMonitoring = false;
  57563. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  57564. if (!BABYLON.Tools.IsWindowObjectExist()) {
  57565. this._gamepadEventSupported = false;
  57566. }
  57567. else {
  57568. this._gamepadEventSupported = 'GamepadEvent' in window;
  57569. this._gamepadSupport = (navigator.getGamepads ||
  57570. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  57571. }
  57572. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  57573. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  57574. for (var i in _this._babylonGamepads) {
  57575. var gamepad = _this._babylonGamepads[i];
  57576. if (gamepad && gamepad._isConnected) {
  57577. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  57578. }
  57579. }
  57580. });
  57581. this._onGamepadConnectedEvent = function (evt) {
  57582. var gamepad = evt.gamepad;
  57583. if (gamepad.index in _this._babylonGamepads) {
  57584. if (_this._babylonGamepads[gamepad.index].isConnected) {
  57585. return;
  57586. }
  57587. }
  57588. var newGamepad;
  57589. if (_this._babylonGamepads[gamepad.index]) {
  57590. newGamepad = _this._babylonGamepads[gamepad.index];
  57591. newGamepad.browserGamepad = gamepad;
  57592. newGamepad._isConnected = true;
  57593. }
  57594. else {
  57595. newGamepad = _this._addNewGamepad(gamepad);
  57596. }
  57597. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57598. _this._startMonitoringGamepads();
  57599. };
  57600. this._onGamepadDisconnectedEvent = function (evt) {
  57601. var gamepad = evt.gamepad;
  57602. // Remove the gamepad from the list of gamepads to monitor.
  57603. for (var i in _this._babylonGamepads) {
  57604. if (_this._babylonGamepads[i].index === gamepad.index) {
  57605. var disconnectedGamepad = _this._babylonGamepads[i];
  57606. disconnectedGamepad._isConnected = false;
  57607. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  57608. break;
  57609. }
  57610. }
  57611. };
  57612. if (this._gamepadSupport) {
  57613. //first add already-connected gamepads
  57614. this._updateGamepadObjects();
  57615. if (this._babylonGamepads.length) {
  57616. this._startMonitoringGamepads();
  57617. }
  57618. // Checking if the gamepad connected event is supported (like in Firefox)
  57619. if (this._gamepadEventSupported) {
  57620. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  57621. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  57622. }
  57623. else {
  57624. this._startMonitoringGamepads();
  57625. }
  57626. }
  57627. }
  57628. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  57629. get: function () {
  57630. return this._babylonGamepads;
  57631. },
  57632. enumerable: true,
  57633. configurable: true
  57634. });
  57635. GamepadManager.prototype.getGamepadByType = function (type) {
  57636. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  57637. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  57638. var gamepad = _a[_i];
  57639. if (gamepad && gamepad.type === type) {
  57640. return gamepad;
  57641. }
  57642. }
  57643. return null;
  57644. };
  57645. GamepadManager.prototype.dispose = function () {
  57646. if (this._gamepadEventSupported) {
  57647. if (this._onGamepadConnectedEvent) {
  57648. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  57649. }
  57650. if (this._onGamepadDisconnectedEvent) {
  57651. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  57652. }
  57653. this._onGamepadConnectedEvent = null;
  57654. this._onGamepadDisconnectedEvent = null;
  57655. }
  57656. this._babylonGamepads.forEach(function (gamepad) {
  57657. gamepad.dispose();
  57658. });
  57659. this.onGamepadConnectedObservable.clear();
  57660. this.onGamepadDisconnectedObservable.clear();
  57661. this._oneGamepadConnected = false;
  57662. this._stopMonitoringGamepads();
  57663. this._babylonGamepads = [];
  57664. };
  57665. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  57666. if (!this._oneGamepadConnected) {
  57667. this._oneGamepadConnected = true;
  57668. }
  57669. var newGamepad;
  57670. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  57671. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  57672. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  57673. }
  57674. else if (gamepad.pose) {
  57675. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  57676. }
  57677. else {
  57678. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  57679. }
  57680. this._babylonGamepads[newGamepad.index] = newGamepad;
  57681. return newGamepad;
  57682. };
  57683. GamepadManager.prototype._startMonitoringGamepads = function () {
  57684. if (!this._isMonitoring) {
  57685. this._isMonitoring = true;
  57686. //back-comp
  57687. if (!this._scene) {
  57688. this._checkGamepadsStatus();
  57689. }
  57690. }
  57691. };
  57692. GamepadManager.prototype._stopMonitoringGamepads = function () {
  57693. this._isMonitoring = false;
  57694. };
  57695. GamepadManager.prototype._checkGamepadsStatus = function () {
  57696. var _this = this;
  57697. // Hack to be compatible Chrome
  57698. this._updateGamepadObjects();
  57699. for (var i in this._babylonGamepads) {
  57700. var gamepad = this._babylonGamepads[i];
  57701. if (!gamepad || !gamepad.isConnected) {
  57702. continue;
  57703. }
  57704. gamepad.update();
  57705. }
  57706. if (this._isMonitoring && !this._scene) {
  57707. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  57708. }
  57709. };
  57710. // This function is called only on Chrome, which does not properly support
  57711. // connection/disconnection events and forces you to recopy again the gamepad object
  57712. GamepadManager.prototype._updateGamepadObjects = function () {
  57713. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  57714. for (var i = 0; i < gamepads.length; i++) {
  57715. if (gamepads[i]) {
  57716. if (!this._babylonGamepads[gamepads[i].index]) {
  57717. var newGamepad = this._addNewGamepad(gamepads[i]);
  57718. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57719. }
  57720. else {
  57721. // Forced to copy again this object for Chrome for unknown reason
  57722. this._babylonGamepads[i].browserGamepad = gamepads[i];
  57723. if (!this._babylonGamepads[i].isConnected) {
  57724. this._babylonGamepads[i]._isConnected = true;
  57725. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  57726. }
  57727. }
  57728. }
  57729. }
  57730. };
  57731. return GamepadManager;
  57732. }());
  57733. BABYLON.GamepadManager = GamepadManager;
  57734. })(BABYLON || (BABYLON = {}));
  57735. //# sourceMappingURL=babylon.gamepadManager.js.map
  57736. var BABYLON;
  57737. (function (BABYLON) {
  57738. var StickValues = /** @class */ (function () {
  57739. function StickValues(x, y) {
  57740. this.x = x;
  57741. this.y = y;
  57742. }
  57743. return StickValues;
  57744. }());
  57745. BABYLON.StickValues = StickValues;
  57746. var Gamepad = /** @class */ (function () {
  57747. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  57748. if (leftStickX === void 0) { leftStickX = 0; }
  57749. if (leftStickY === void 0) { leftStickY = 1; }
  57750. if (rightStickX === void 0) { rightStickX = 2; }
  57751. if (rightStickY === void 0) { rightStickY = 3; }
  57752. this.id = id;
  57753. this.index = index;
  57754. this.browserGamepad = browserGamepad;
  57755. this._isConnected = true;
  57756. this._invertLeftStickY = false;
  57757. this.type = Gamepad.GAMEPAD;
  57758. this._leftStickAxisX = leftStickX;
  57759. this._leftStickAxisY = leftStickY;
  57760. this._rightStickAxisX = rightStickX;
  57761. this._rightStickAxisY = rightStickY;
  57762. if (this.browserGamepad.axes.length >= 2) {
  57763. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57764. }
  57765. if (this.browserGamepad.axes.length >= 4) {
  57766. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57767. }
  57768. }
  57769. Object.defineProperty(Gamepad.prototype, "isConnected", {
  57770. get: function () {
  57771. return this._isConnected;
  57772. },
  57773. enumerable: true,
  57774. configurable: true
  57775. });
  57776. Gamepad.prototype.onleftstickchanged = function (callback) {
  57777. this._onleftstickchanged = callback;
  57778. };
  57779. Gamepad.prototype.onrightstickchanged = function (callback) {
  57780. this._onrightstickchanged = callback;
  57781. };
  57782. Object.defineProperty(Gamepad.prototype, "leftStick", {
  57783. get: function () {
  57784. return this._leftStick;
  57785. },
  57786. set: function (newValues) {
  57787. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  57788. this._onleftstickchanged(newValues);
  57789. }
  57790. this._leftStick = newValues;
  57791. },
  57792. enumerable: true,
  57793. configurable: true
  57794. });
  57795. Object.defineProperty(Gamepad.prototype, "rightStick", {
  57796. get: function () {
  57797. return this._rightStick;
  57798. },
  57799. set: function (newValues) {
  57800. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  57801. this._onrightstickchanged(newValues);
  57802. }
  57803. this._rightStick = newValues;
  57804. },
  57805. enumerable: true,
  57806. configurable: true
  57807. });
  57808. Gamepad.prototype.update = function () {
  57809. if (this._leftStick) {
  57810. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57811. if (this._invertLeftStickY) {
  57812. this.leftStick.y *= -1;
  57813. }
  57814. }
  57815. if (this._rightStick) {
  57816. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57817. }
  57818. };
  57819. Gamepad.prototype.dispose = function () {
  57820. };
  57821. Gamepad.GAMEPAD = 0;
  57822. Gamepad.GENERIC = 1;
  57823. Gamepad.XBOX = 2;
  57824. Gamepad.POSE_ENABLED = 3;
  57825. return Gamepad;
  57826. }());
  57827. BABYLON.Gamepad = Gamepad;
  57828. var GenericPad = /** @class */ (function (_super) {
  57829. __extends(GenericPad, _super);
  57830. function GenericPad(id, index, browserGamepad) {
  57831. var _this = _super.call(this, id, index, browserGamepad) || this;
  57832. _this.onButtonDownObservable = new BABYLON.Observable();
  57833. _this.onButtonUpObservable = new BABYLON.Observable();
  57834. _this.type = Gamepad.GENERIC;
  57835. _this._buttons = new Array(browserGamepad.buttons.length);
  57836. return _this;
  57837. }
  57838. GenericPad.prototype.onbuttondown = function (callback) {
  57839. this._onbuttondown = callback;
  57840. };
  57841. GenericPad.prototype.onbuttonup = function (callback) {
  57842. this._onbuttonup = callback;
  57843. };
  57844. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  57845. if (newValue !== currentValue) {
  57846. if (newValue === 1) {
  57847. if (this._onbuttondown) {
  57848. this._onbuttondown(buttonIndex);
  57849. }
  57850. this.onButtonDownObservable.notifyObservers(buttonIndex);
  57851. }
  57852. if (newValue === 0) {
  57853. if (this._onbuttonup) {
  57854. this._onbuttonup(buttonIndex);
  57855. }
  57856. this.onButtonUpObservable.notifyObservers(buttonIndex);
  57857. }
  57858. }
  57859. return newValue;
  57860. };
  57861. GenericPad.prototype.update = function () {
  57862. _super.prototype.update.call(this);
  57863. for (var index = 0; index < this._buttons.length; index++) {
  57864. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  57865. }
  57866. };
  57867. GenericPad.prototype.dispose = function () {
  57868. _super.prototype.dispose.call(this);
  57869. this.onButtonDownObservable.clear();
  57870. this.onButtonUpObservable.clear();
  57871. };
  57872. return GenericPad;
  57873. }(Gamepad));
  57874. BABYLON.GenericPad = GenericPad;
  57875. })(BABYLON || (BABYLON = {}));
  57876. //# sourceMappingURL=babylon.gamepad.js.map
  57877. var BABYLON;
  57878. (function (BABYLON) {
  57879. var Xbox360Button;
  57880. (function (Xbox360Button) {
  57881. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  57882. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  57883. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  57884. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  57885. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  57886. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  57887. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  57888. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  57889. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  57890. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  57891. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  57892. var Xbox360Dpad;
  57893. (function (Xbox360Dpad) {
  57894. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  57895. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  57896. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  57897. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  57898. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  57899. var Xbox360Pad = /** @class */ (function (_super) {
  57900. __extends(Xbox360Pad, _super);
  57901. function Xbox360Pad(id, index, gamepad, xboxOne) {
  57902. if (xboxOne === void 0) { xboxOne = false; }
  57903. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  57904. _this._leftTrigger = 0;
  57905. _this._rightTrigger = 0;
  57906. _this.onButtonDownObservable = new BABYLON.Observable();
  57907. _this.onButtonUpObservable = new BABYLON.Observable();
  57908. _this.onPadDownObservable = new BABYLON.Observable();
  57909. _this.onPadUpObservable = new BABYLON.Observable();
  57910. _this._buttonA = 0;
  57911. _this._buttonB = 0;
  57912. _this._buttonX = 0;
  57913. _this._buttonY = 0;
  57914. _this._buttonBack = 0;
  57915. _this._buttonStart = 0;
  57916. _this._buttonLB = 0;
  57917. _this._buttonRB = 0;
  57918. _this._buttonLeftStick = 0;
  57919. _this._buttonRightStick = 0;
  57920. _this._dPadUp = 0;
  57921. _this._dPadDown = 0;
  57922. _this._dPadLeft = 0;
  57923. _this._dPadRight = 0;
  57924. _this._isXboxOnePad = false;
  57925. _this.type = BABYLON.Gamepad.XBOX;
  57926. _this._isXboxOnePad = xboxOne;
  57927. return _this;
  57928. }
  57929. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  57930. this._onlefttriggerchanged = callback;
  57931. };
  57932. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  57933. this._onrighttriggerchanged = callback;
  57934. };
  57935. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  57936. get: function () {
  57937. return this._leftTrigger;
  57938. },
  57939. set: function (newValue) {
  57940. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  57941. this._onlefttriggerchanged(newValue);
  57942. }
  57943. this._leftTrigger = newValue;
  57944. },
  57945. enumerable: true,
  57946. configurable: true
  57947. });
  57948. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  57949. get: function () {
  57950. return this._rightTrigger;
  57951. },
  57952. set: function (newValue) {
  57953. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  57954. this._onrighttriggerchanged(newValue);
  57955. }
  57956. this._rightTrigger = newValue;
  57957. },
  57958. enumerable: true,
  57959. configurable: true
  57960. });
  57961. Xbox360Pad.prototype.onbuttondown = function (callback) {
  57962. this._onbuttondown = callback;
  57963. };
  57964. Xbox360Pad.prototype.onbuttonup = function (callback) {
  57965. this._onbuttonup = callback;
  57966. };
  57967. Xbox360Pad.prototype.ondpaddown = function (callback) {
  57968. this._ondpaddown = callback;
  57969. };
  57970. Xbox360Pad.prototype.ondpadup = function (callback) {
  57971. this._ondpadup = callback;
  57972. };
  57973. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  57974. if (newValue !== currentValue) {
  57975. if (newValue === 1) {
  57976. if (this._onbuttondown) {
  57977. this._onbuttondown(buttonType);
  57978. }
  57979. this.onButtonDownObservable.notifyObservers(buttonType);
  57980. }
  57981. if (newValue === 0) {
  57982. if (this._onbuttonup) {
  57983. this._onbuttonup(buttonType);
  57984. }
  57985. this.onButtonUpObservable.notifyObservers(buttonType);
  57986. }
  57987. }
  57988. return newValue;
  57989. };
  57990. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  57991. if (newValue !== currentValue) {
  57992. if (newValue === 1) {
  57993. if (this._ondpaddown) {
  57994. this._ondpaddown(buttonType);
  57995. }
  57996. this.onPadDownObservable.notifyObservers(buttonType);
  57997. }
  57998. if (newValue === 0) {
  57999. if (this._ondpadup) {
  58000. this._ondpadup(buttonType);
  58001. }
  58002. this.onPadUpObservable.notifyObservers(buttonType);
  58003. }
  58004. }
  58005. return newValue;
  58006. };
  58007. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  58008. get: function () {
  58009. return this._buttonA;
  58010. },
  58011. set: function (value) {
  58012. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  58013. },
  58014. enumerable: true,
  58015. configurable: true
  58016. });
  58017. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  58018. get: function () {
  58019. return this._buttonB;
  58020. },
  58021. set: function (value) {
  58022. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  58023. },
  58024. enumerable: true,
  58025. configurable: true
  58026. });
  58027. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  58028. get: function () {
  58029. return this._buttonX;
  58030. },
  58031. set: function (value) {
  58032. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  58033. },
  58034. enumerable: true,
  58035. configurable: true
  58036. });
  58037. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  58038. get: function () {
  58039. return this._buttonY;
  58040. },
  58041. set: function (value) {
  58042. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  58043. },
  58044. enumerable: true,
  58045. configurable: true
  58046. });
  58047. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  58048. get: function () {
  58049. return this._buttonStart;
  58050. },
  58051. set: function (value) {
  58052. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  58053. },
  58054. enumerable: true,
  58055. configurable: true
  58056. });
  58057. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  58058. get: function () {
  58059. return this._buttonBack;
  58060. },
  58061. set: function (value) {
  58062. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  58063. },
  58064. enumerable: true,
  58065. configurable: true
  58066. });
  58067. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  58068. get: function () {
  58069. return this._buttonLB;
  58070. },
  58071. set: function (value) {
  58072. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  58073. },
  58074. enumerable: true,
  58075. configurable: true
  58076. });
  58077. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  58078. get: function () {
  58079. return this._buttonRB;
  58080. },
  58081. set: function (value) {
  58082. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  58083. },
  58084. enumerable: true,
  58085. configurable: true
  58086. });
  58087. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  58088. get: function () {
  58089. return this._buttonLeftStick;
  58090. },
  58091. set: function (value) {
  58092. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  58093. },
  58094. enumerable: true,
  58095. configurable: true
  58096. });
  58097. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  58098. get: function () {
  58099. return this._buttonRightStick;
  58100. },
  58101. set: function (value) {
  58102. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  58103. },
  58104. enumerable: true,
  58105. configurable: true
  58106. });
  58107. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  58108. get: function () {
  58109. return this._dPadUp;
  58110. },
  58111. set: function (value) {
  58112. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  58113. },
  58114. enumerable: true,
  58115. configurable: true
  58116. });
  58117. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  58118. get: function () {
  58119. return this._dPadDown;
  58120. },
  58121. set: function (value) {
  58122. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  58123. },
  58124. enumerable: true,
  58125. configurable: true
  58126. });
  58127. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  58128. get: function () {
  58129. return this._dPadLeft;
  58130. },
  58131. set: function (value) {
  58132. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  58133. },
  58134. enumerable: true,
  58135. configurable: true
  58136. });
  58137. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  58138. get: function () {
  58139. return this._dPadRight;
  58140. },
  58141. set: function (value) {
  58142. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  58143. },
  58144. enumerable: true,
  58145. configurable: true
  58146. });
  58147. Xbox360Pad.prototype.update = function () {
  58148. _super.prototype.update.call(this);
  58149. if (this._isXboxOnePad) {
  58150. this.buttonA = this.browserGamepad.buttons[0].value;
  58151. this.buttonB = this.browserGamepad.buttons[1].value;
  58152. this.buttonX = this.browserGamepad.buttons[2].value;
  58153. this.buttonY = this.browserGamepad.buttons[3].value;
  58154. this.buttonLB = this.browserGamepad.buttons[4].value;
  58155. this.buttonRB = this.browserGamepad.buttons[5].value;
  58156. this.leftTrigger = this.browserGamepad.axes[2];
  58157. this.rightTrigger = this.browserGamepad.axes[5];
  58158. this.buttonBack = this.browserGamepad.buttons[9].value;
  58159. this.buttonStart = this.browserGamepad.buttons[8].value;
  58160. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  58161. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  58162. this.dPadUp = this.browserGamepad.buttons[11].value;
  58163. this.dPadDown = this.browserGamepad.buttons[12].value;
  58164. this.dPadLeft = this.browserGamepad.buttons[13].value;
  58165. this.dPadRight = this.browserGamepad.buttons[14].value;
  58166. }
  58167. else {
  58168. this.buttonA = this.browserGamepad.buttons[0].value;
  58169. this.buttonB = this.browserGamepad.buttons[1].value;
  58170. this.buttonX = this.browserGamepad.buttons[2].value;
  58171. this.buttonY = this.browserGamepad.buttons[3].value;
  58172. this.buttonLB = this.browserGamepad.buttons[4].value;
  58173. this.buttonRB = this.browserGamepad.buttons[5].value;
  58174. this.leftTrigger = this.browserGamepad.buttons[6].value;
  58175. this.rightTrigger = this.browserGamepad.buttons[7].value;
  58176. this.buttonBack = this.browserGamepad.buttons[8].value;
  58177. this.buttonStart = this.browserGamepad.buttons[9].value;
  58178. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  58179. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  58180. this.dPadUp = this.browserGamepad.buttons[12].value;
  58181. this.dPadDown = this.browserGamepad.buttons[13].value;
  58182. this.dPadLeft = this.browserGamepad.buttons[14].value;
  58183. this.dPadRight = this.browserGamepad.buttons[15].value;
  58184. }
  58185. };
  58186. Xbox360Pad.prototype.dispose = function () {
  58187. _super.prototype.dispose.call(this);
  58188. this.onButtonDownObservable.clear();
  58189. this.onButtonUpObservable.clear();
  58190. this.onPadDownObservable.clear();
  58191. this.onPadUpObservable.clear();
  58192. };
  58193. return Xbox360Pad;
  58194. }(BABYLON.Gamepad));
  58195. BABYLON.Xbox360Pad = Xbox360Pad;
  58196. })(BABYLON || (BABYLON = {}));
  58197. //# sourceMappingURL=babylon.xboxGamepad.js.map
  58198. var BABYLON;
  58199. (function (BABYLON) {
  58200. var PoseEnabledControllerType;
  58201. (function (PoseEnabledControllerType) {
  58202. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  58203. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  58204. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  58205. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  58206. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  58207. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  58208. var PoseEnabledControllerHelper = /** @class */ (function () {
  58209. function PoseEnabledControllerHelper() {
  58210. }
  58211. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  58212. // Oculus Touch
  58213. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  58214. return new BABYLON.OculusTouchController(vrGamepad);
  58215. }
  58216. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  58217. return new BABYLON.WindowsMotionController(vrGamepad);
  58218. }
  58219. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  58220. return new BABYLON.ViveController(vrGamepad);
  58221. }
  58222. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  58223. return new BABYLON.GearVRController(vrGamepad);
  58224. }
  58225. else {
  58226. return new BABYLON.GenericController(vrGamepad);
  58227. }
  58228. };
  58229. return PoseEnabledControllerHelper;
  58230. }());
  58231. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  58232. var PoseEnabledController = /** @class */ (function (_super) {
  58233. __extends(PoseEnabledController, _super);
  58234. function PoseEnabledController(browserGamepad) {
  58235. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  58236. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  58237. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  58238. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  58239. // Represents device position and rotation in babylon space
  58240. _this.devicePosition = BABYLON.Vector3.Zero();
  58241. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  58242. _this.deviceScaleFactor = 1;
  58243. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  58244. _this._deviceToWorld = BABYLON.Matrix.Identity();
  58245. _this._workingMatrix = BABYLON.Matrix.Identity();
  58246. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  58247. _this.controllerType = PoseEnabledControllerType.GENERIC;
  58248. _this.position = BABYLON.Vector3.Zero();
  58249. _this.rotationQuaternion = new BABYLON.Quaternion();
  58250. _this._calculatedPosition = BABYLON.Vector3.Zero();
  58251. _this._calculatedRotation = new BABYLON.Quaternion();
  58252. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  58253. return _this;
  58254. }
  58255. PoseEnabledController.prototype.update = function () {
  58256. _super.prototype.update.call(this);
  58257. var pose = this.browserGamepad.pose;
  58258. this.updateFromDevice(pose);
  58259. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  58260. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  58261. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  58262. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  58263. if (this._mesh) {
  58264. this._mesh.position.copyFrom(this.devicePosition);
  58265. if (this._mesh.rotationQuaternion) {
  58266. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  58267. }
  58268. }
  58269. };
  58270. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  58271. if (poseData) {
  58272. this.rawPose = poseData;
  58273. if (poseData.position) {
  58274. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  58275. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  58276. this._deviceRoomPosition.z *= -1;
  58277. }
  58278. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  58279. this._calculatedPosition.addInPlace(this.position);
  58280. }
  58281. var pose = this.rawPose;
  58282. if (poseData.orientation && pose.orientation) {
  58283. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  58284. if (this._mesh) {
  58285. if (this._mesh.getScene().useRightHandedSystem) {
  58286. this._deviceRoomRotationQuaternion.z *= -1;
  58287. this._deviceRoomRotationQuaternion.w *= -1;
  58288. }
  58289. else {
  58290. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  58291. }
  58292. }
  58293. // if the camera is set, rotate to the camera's rotation
  58294. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  58295. }
  58296. }
  58297. };
  58298. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  58299. if (this._mesh) {
  58300. this._mesh.parent = null;
  58301. }
  58302. this._mesh = mesh;
  58303. if (this._poseControlledCamera) {
  58304. this._mesh.parent = this._poseControlledCamera;
  58305. }
  58306. if (!this._mesh.rotationQuaternion) {
  58307. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  58308. }
  58309. };
  58310. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  58311. this._poseControlledCamera = camera;
  58312. if (this._mesh) {
  58313. this._mesh.parent = this._poseControlledCamera;
  58314. }
  58315. };
  58316. PoseEnabledController.prototype.dispose = function () {
  58317. if (this._mesh) {
  58318. this._mesh.dispose();
  58319. }
  58320. this._mesh = null;
  58321. _super.prototype.dispose.call(this);
  58322. };
  58323. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  58324. get: function () {
  58325. return this._mesh;
  58326. },
  58327. enumerable: true,
  58328. configurable: true
  58329. });
  58330. PoseEnabledController.prototype.getForwardRay = function (length) {
  58331. if (length === void 0) { length = 100; }
  58332. if (!this.mesh) {
  58333. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  58334. }
  58335. var m = this.mesh.getWorldMatrix();
  58336. var origin = m.getTranslation();
  58337. var forward = new BABYLON.Vector3(0, 0, -1);
  58338. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  58339. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  58340. return new BABYLON.Ray(origin, direction, length);
  58341. };
  58342. return PoseEnabledController;
  58343. }(BABYLON.Gamepad));
  58344. BABYLON.PoseEnabledController = PoseEnabledController;
  58345. })(BABYLON || (BABYLON = {}));
  58346. //# sourceMappingURL=babylon.poseEnabledController.js.map
  58347. var BABYLON;
  58348. (function (BABYLON) {
  58349. var WebVRController = /** @class */ (function (_super) {
  58350. __extends(WebVRController, _super);
  58351. function WebVRController(vrGamepad) {
  58352. var _this = _super.call(this, vrGamepad) || this;
  58353. // Observables
  58354. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  58355. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  58356. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  58357. _this.onPadStateChangedObservable = new BABYLON.Observable();
  58358. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  58359. _this.pad = { x: 0, y: 0 };
  58360. // avoid GC, store state in a tmp object
  58361. _this._changes = {
  58362. pressChanged: false,
  58363. touchChanged: false,
  58364. valueChanged: false,
  58365. changed: false
  58366. };
  58367. _this._buttons = new Array(vrGamepad.buttons.length);
  58368. _this.hand = vrGamepad.hand;
  58369. return _this;
  58370. }
  58371. WebVRController.prototype.onButtonStateChange = function (callback) {
  58372. this._onButtonStateChange = callback;
  58373. };
  58374. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  58375. get: function () {
  58376. return this._defaultModel;
  58377. },
  58378. enumerable: true,
  58379. configurable: true
  58380. });
  58381. WebVRController.prototype.update = function () {
  58382. _super.prototype.update.call(this);
  58383. for (var index = 0; index < this._buttons.length; index++) {
  58384. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  58385. }
  58386. ;
  58387. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  58388. this.pad.x = this.leftStick.x;
  58389. this.pad.y = this.leftStick.y;
  58390. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  58391. }
  58392. };
  58393. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  58394. if (!newState) {
  58395. newState = {
  58396. pressed: false,
  58397. touched: false,
  58398. value: 0
  58399. };
  58400. }
  58401. if (!currentState) {
  58402. this._buttons[buttonIndex] = {
  58403. pressed: newState.pressed,
  58404. touched: newState.touched,
  58405. value: newState.value
  58406. };
  58407. return;
  58408. }
  58409. this._checkChanges(newState, currentState);
  58410. if (this._changes.changed) {
  58411. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  58412. this.handleButtonChange(buttonIndex, newState, this._changes);
  58413. }
  58414. this._buttons[buttonIndex].pressed = newState.pressed;
  58415. this._buttons[buttonIndex].touched = newState.touched;
  58416. // oculus triggers are never 0, thou not touched.
  58417. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  58418. };
  58419. WebVRController.prototype._checkChanges = function (newState, currentState) {
  58420. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  58421. this._changes.touchChanged = newState.touched !== currentState.touched;
  58422. this._changes.valueChanged = newState.value !== currentState.value;
  58423. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  58424. return this._changes;
  58425. };
  58426. WebVRController.prototype.dispose = function () {
  58427. _super.prototype.dispose.call(this);
  58428. this.onTriggerStateChangedObservable.clear();
  58429. this.onMainButtonStateChangedObservable.clear();
  58430. this.onSecondaryButtonStateChangedObservable.clear();
  58431. this.onPadStateChangedObservable.clear();
  58432. this.onPadValuesChangedObservable.clear();
  58433. };
  58434. return WebVRController;
  58435. }(BABYLON.PoseEnabledController));
  58436. BABYLON.WebVRController = WebVRController;
  58437. })(BABYLON || (BABYLON = {}));
  58438. //# sourceMappingURL=babylon.webVRController.js.map
  58439. var BABYLON;
  58440. (function (BABYLON) {
  58441. var OculusTouchController = /** @class */ (function (_super) {
  58442. __extends(OculusTouchController, _super);
  58443. function OculusTouchController(vrGamepad) {
  58444. var _this = _super.call(this, vrGamepad) || this;
  58445. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  58446. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  58447. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  58448. return _this;
  58449. }
  58450. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58451. var _this = this;
  58452. var meshName;
  58453. // Hand
  58454. if (this.hand === 'left') {
  58455. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  58456. }
  58457. else {
  58458. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  58459. }
  58460. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  58461. /*
  58462. Parent Mesh name: oculus_touch_left
  58463. - body
  58464. - trigger
  58465. - thumbstick
  58466. - grip
  58467. - button_y
  58468. - button_x
  58469. - button_enter
  58470. */
  58471. _this._defaultModel = newMeshes[1];
  58472. _this.attachToMesh(_this._defaultModel);
  58473. if (meshLoaded) {
  58474. meshLoaded(_this._defaultModel);
  58475. }
  58476. });
  58477. };
  58478. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  58479. // helper getters for left and right hand.
  58480. get: function () {
  58481. if (this.hand === 'right') {
  58482. return this.onMainButtonStateChangedObservable;
  58483. }
  58484. else {
  58485. throw new Error('No A button on left hand');
  58486. }
  58487. },
  58488. enumerable: true,
  58489. configurable: true
  58490. });
  58491. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  58492. get: function () {
  58493. if (this.hand === 'right') {
  58494. return this.onSecondaryButtonStateChangedObservable;
  58495. }
  58496. else {
  58497. throw new Error('No B button on left hand');
  58498. }
  58499. },
  58500. enumerable: true,
  58501. configurable: true
  58502. });
  58503. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  58504. get: function () {
  58505. if (this.hand === 'left') {
  58506. return this.onMainButtonStateChangedObservable;
  58507. }
  58508. else {
  58509. throw new Error('No X button on right hand');
  58510. }
  58511. },
  58512. enumerable: true,
  58513. configurable: true
  58514. });
  58515. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  58516. get: function () {
  58517. if (this.hand === 'left') {
  58518. return this.onSecondaryButtonStateChangedObservable;
  58519. }
  58520. else {
  58521. throw new Error('No Y button on right hand');
  58522. }
  58523. },
  58524. enumerable: true,
  58525. configurable: true
  58526. });
  58527. /*
  58528. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  58529. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  58530. 2) secondary trigger (same)
  58531. 3) A (right) X (left), touch, pressed = value
  58532. 4) B / Y
  58533. 5) thumb rest
  58534. */
  58535. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58536. var notifyObject = state; //{ state: state, changes: changes };
  58537. var triggerDirection = this.hand === 'right' ? -1 : 1;
  58538. switch (buttonIdx) {
  58539. case 0:
  58540. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58541. return;
  58542. case 1:// index trigger
  58543. if (this._defaultModel) {
  58544. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  58545. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  58546. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  58547. }
  58548. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58549. return;
  58550. case 2:// secondary trigger
  58551. if (this._defaultModel) {
  58552. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  58553. }
  58554. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  58555. return;
  58556. case 3:
  58557. if (this._defaultModel) {
  58558. if (notifyObject.pressed) {
  58559. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  58560. }
  58561. else {
  58562. (this._defaultModel.getChildren()[1]).position.y = 0;
  58563. }
  58564. }
  58565. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58566. return;
  58567. case 4:
  58568. if (this._defaultModel) {
  58569. if (notifyObject.pressed) {
  58570. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58571. }
  58572. else {
  58573. (this._defaultModel.getChildren()[2]).position.y = 0;
  58574. }
  58575. }
  58576. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58577. return;
  58578. case 5:
  58579. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  58580. return;
  58581. }
  58582. };
  58583. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  58584. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  58585. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  58586. return OculusTouchController;
  58587. }(BABYLON.WebVRController));
  58588. BABYLON.OculusTouchController = OculusTouchController;
  58589. })(BABYLON || (BABYLON = {}));
  58590. //# sourceMappingURL=babylon.oculusTouchController.js.map
  58591. var BABYLON;
  58592. (function (BABYLON) {
  58593. var ViveController = /** @class */ (function (_super) {
  58594. __extends(ViveController, _super);
  58595. function ViveController(vrGamepad) {
  58596. var _this = _super.call(this, vrGamepad) || this;
  58597. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  58598. _this._invertLeftStickY = true;
  58599. return _this;
  58600. }
  58601. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58602. var _this = this;
  58603. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  58604. /*
  58605. Parent Mesh name: ViveWand
  58606. - body
  58607. - r_gripper
  58608. - l_gripper
  58609. - menu_button
  58610. - system_button
  58611. - trackpad
  58612. - trigger
  58613. - LED
  58614. */
  58615. _this._defaultModel = newMeshes[1];
  58616. _this.attachToMesh(_this._defaultModel);
  58617. if (meshLoaded) {
  58618. meshLoaded(_this._defaultModel);
  58619. }
  58620. });
  58621. };
  58622. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  58623. get: function () {
  58624. return this.onMainButtonStateChangedObservable;
  58625. },
  58626. enumerable: true,
  58627. configurable: true
  58628. });
  58629. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  58630. get: function () {
  58631. return this.onMainButtonStateChangedObservable;
  58632. },
  58633. enumerable: true,
  58634. configurable: true
  58635. });
  58636. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  58637. get: function () {
  58638. return this.onSecondaryButtonStateChangedObservable;
  58639. },
  58640. enumerable: true,
  58641. configurable: true
  58642. });
  58643. /**
  58644. * Vive mapping:
  58645. * 0: touchpad
  58646. * 1: trigger
  58647. * 2: left AND right buttons
  58648. * 3: menu button
  58649. */
  58650. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58651. var notifyObject = state; //{ state: state, changes: changes };
  58652. switch (buttonIdx) {
  58653. case 0:
  58654. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58655. return;
  58656. case 1:// index trigger
  58657. if (this._defaultModel) {
  58658. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  58659. }
  58660. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58661. return;
  58662. case 2:// left AND right button
  58663. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58664. return;
  58665. case 3:
  58666. if (this._defaultModel) {
  58667. if (notifyObject.pressed) {
  58668. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58669. }
  58670. else {
  58671. (this._defaultModel.getChildren()[2]).position.y = 0;
  58672. }
  58673. }
  58674. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58675. return;
  58676. }
  58677. };
  58678. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  58679. ViveController.MODEL_FILENAME = 'wand.babylon';
  58680. return ViveController;
  58681. }(BABYLON.WebVRController));
  58682. BABYLON.ViveController = ViveController;
  58683. })(BABYLON || (BABYLON = {}));
  58684. //# sourceMappingURL=babylon.viveController.js.map
  58685. var BABYLON;
  58686. (function (BABYLON) {
  58687. var GenericController = /** @class */ (function (_super) {
  58688. __extends(GenericController, _super);
  58689. function GenericController(vrGamepad) {
  58690. return _super.call(this, vrGamepad) || this;
  58691. }
  58692. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58693. var _this = this;
  58694. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  58695. _this._defaultModel = newMeshes[1];
  58696. _this.attachToMesh(_this._defaultModel);
  58697. if (meshLoaded) {
  58698. meshLoaded(_this._defaultModel);
  58699. }
  58700. });
  58701. };
  58702. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58703. console.log("Button id: " + buttonIdx + "state: ");
  58704. console.dir(state);
  58705. };
  58706. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  58707. GenericController.MODEL_FILENAME = 'generic.babylon';
  58708. return GenericController;
  58709. }(BABYLON.WebVRController));
  58710. BABYLON.GenericController = GenericController;
  58711. })(BABYLON || (BABYLON = {}));
  58712. //# sourceMappingURL=babylon.genericController.js.map
  58713. var BABYLON;
  58714. (function (BABYLON) {
  58715. var LoadedMeshInfo = /** @class */ (function () {
  58716. function LoadedMeshInfo() {
  58717. this.buttonMeshes = {};
  58718. this.axisMeshes = {};
  58719. }
  58720. return LoadedMeshInfo;
  58721. }());
  58722. var WindowsMotionController = /** @class */ (function (_super) {
  58723. __extends(WindowsMotionController, _super);
  58724. function WindowsMotionController(vrGamepad) {
  58725. var _this = _super.call(this, vrGamepad) || this;
  58726. _this._mapping = {
  58727. // Semantic button names
  58728. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  58729. // A mapping of the button name to glTF model node name
  58730. // that should be transformed by button value.
  58731. buttonMeshNames: {
  58732. 'trigger': 'SELECT',
  58733. 'menu': 'MENU',
  58734. 'grip': 'GRASP',
  58735. 'thumbstick': 'THUMBSTICK_PRESS',
  58736. 'trackpad': 'TOUCHPAD_PRESS'
  58737. },
  58738. // This mapping is used to translate from the Motion Controller to Babylon semantics
  58739. buttonObservableNames: {
  58740. 'trigger': 'onTriggerStateChangedObservable',
  58741. 'menu': 'onSecondaryButtonStateChangedObservable',
  58742. 'grip': 'onMainButtonStateChangedObservable',
  58743. 'thumbstick': 'onPadStateChangedObservable',
  58744. 'trackpad': 'onTrackpadChangedObservable'
  58745. },
  58746. // A mapping of the axis name to glTF model node name
  58747. // that should be transformed by axis value.
  58748. // This array mirrors the browserGamepad.axes array, such that
  58749. // the mesh corresponding to axis 0 is in this array index 0.
  58750. axisMeshNames: [
  58751. 'THUMBSTICK_X',
  58752. 'THUMBSTICK_Y',
  58753. 'TOUCHPAD_TOUCH_X',
  58754. 'TOUCHPAD_TOUCH_Y'
  58755. ],
  58756. pointingPoseMeshName: 'POINTING_POSE'
  58757. };
  58758. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  58759. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  58760. _this.trackpad = { x: 0, y: 0 };
  58761. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  58762. _this._loadedMeshInfo = null;
  58763. return _this;
  58764. }
  58765. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  58766. get: function () {
  58767. return this.onTriggerStateChangedObservable;
  58768. },
  58769. enumerable: true,
  58770. configurable: true
  58771. });
  58772. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  58773. get: function () {
  58774. return this.onSecondaryButtonStateChangedObservable;
  58775. },
  58776. enumerable: true,
  58777. configurable: true
  58778. });
  58779. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  58780. get: function () {
  58781. return this.onMainButtonStateChangedObservable;
  58782. },
  58783. enumerable: true,
  58784. configurable: true
  58785. });
  58786. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  58787. get: function () {
  58788. return this.onPadStateChangedObservable;
  58789. },
  58790. enumerable: true,
  58791. configurable: true
  58792. });
  58793. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  58794. get: function () {
  58795. return this.onTrackpadChangedObservable;
  58796. },
  58797. enumerable: true,
  58798. configurable: true
  58799. });
  58800. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  58801. get: function () {
  58802. return this.onTrackpadValuesChangedObservable;
  58803. },
  58804. enumerable: true,
  58805. configurable: true
  58806. });
  58807. /**
  58808. * Called once per frame by the engine.
  58809. */
  58810. WindowsMotionController.prototype.update = function () {
  58811. _super.prototype.update.call(this);
  58812. // Only need to animate axes if there is a loaded mesh
  58813. if (this._loadedMeshInfo) {
  58814. if (this.browserGamepad.axes) {
  58815. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  58816. this.trackpad.x = this.browserGamepad["axes"][2];
  58817. this.trackpad.y = this.browserGamepad["axes"][3];
  58818. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  58819. }
  58820. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  58821. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  58822. }
  58823. }
  58824. }
  58825. };
  58826. /**
  58827. * Called once for each button that changed state since the last frame
  58828. * @param buttonIdx Which button index changed
  58829. * @param state New state of the button
  58830. * @param changes Which properties on the state changed since last frame
  58831. */
  58832. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58833. var buttonName = this._mapping.buttons[buttonIdx];
  58834. if (!buttonName) {
  58835. return;
  58836. }
  58837. // Only emit events for buttons that we know how to map from index to name
  58838. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  58839. if (observable) {
  58840. observable.notifyObservers(state);
  58841. }
  58842. this.lerpButtonTransform(buttonName, state.value);
  58843. };
  58844. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  58845. // If there is no loaded mesh, there is nothing to transform.
  58846. if (!this._loadedMeshInfo) {
  58847. return;
  58848. }
  58849. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  58850. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  58851. return;
  58852. }
  58853. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  58854. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  58855. };
  58856. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  58857. if (!this._loadedMeshInfo) {
  58858. return;
  58859. }
  58860. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  58861. if (!meshInfo) {
  58862. return;
  58863. }
  58864. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  58865. return;
  58866. }
  58867. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  58868. var lerpValue = axisValue * 0.5 + 0.5;
  58869. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  58870. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  58871. };
  58872. /**
  58873. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  58874. * @param scene scene in which to add meshes
  58875. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  58876. */
  58877. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  58878. var _this = this;
  58879. if (forceDefault === void 0) { forceDefault = false; }
  58880. var path;
  58881. var filename;
  58882. // Checking if GLB loader is present
  58883. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  58884. // Determine the device specific folder based on the ID suffix
  58885. var device = 'default';
  58886. if (this.id && !forceDefault) {
  58887. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  58888. device = ((match && match[0]) || device);
  58889. }
  58890. // Hand
  58891. if (this.hand === 'left') {
  58892. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  58893. }
  58894. else {
  58895. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  58896. }
  58897. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  58898. }
  58899. else {
  58900. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  58901. path = BABYLON.GenericController.MODEL_BASE_URL;
  58902. filename = BABYLON.GenericController.MODEL_FILENAME;
  58903. }
  58904. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  58905. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  58906. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  58907. if (!_this._loadedMeshInfo) {
  58908. return;
  58909. }
  58910. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  58911. _this.attachToMesh(_this._defaultModel);
  58912. if (meshLoaded) {
  58913. meshLoaded(_this._defaultModel);
  58914. }
  58915. }, null, function (scene, message) {
  58916. BABYLON.Tools.Log(message);
  58917. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  58918. if (!forceDefault) {
  58919. _this.initControllerMesh(scene, meshLoaded, true);
  58920. }
  58921. });
  58922. };
  58923. /**
  58924. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  58925. * can be transformed by button presses and axes values, based on this._mapping.
  58926. *
  58927. * @param scene scene in which the meshes exist
  58928. * @param meshes list of meshes that make up the controller model to process
  58929. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  58930. */
  58931. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  58932. var loadedMeshInfo = null;
  58933. // Create a new mesh to contain the glTF hierarchy
  58934. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  58935. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  58936. var childMesh = null;
  58937. for (var i = 0; i < meshes.length; i++) {
  58938. var mesh = meshes[i];
  58939. if (!mesh.parent) {
  58940. // Exclude controller meshes from picking results
  58941. mesh.isPickable = false;
  58942. // Handle root node, attach to the new parentMesh
  58943. childMesh = mesh;
  58944. break;
  58945. }
  58946. }
  58947. if (childMesh) {
  58948. childMesh.setParent(parentMesh);
  58949. // Create our mesh info. Note that this method will always return non-null.
  58950. loadedMeshInfo = this.createMeshInfo(parentMesh);
  58951. }
  58952. else {
  58953. BABYLON.Tools.Warn('Could not find root node in model file.');
  58954. }
  58955. return loadedMeshInfo;
  58956. };
  58957. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  58958. var loadedMeshInfo = new LoadedMeshInfo();
  58959. var i;
  58960. loadedMeshInfo.rootNode = rootNode;
  58961. // Reset the caches
  58962. loadedMeshInfo.buttonMeshes = {};
  58963. loadedMeshInfo.axisMeshes = {};
  58964. // Button Meshes
  58965. for (i = 0; i < this._mapping.buttons.length; i++) {
  58966. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  58967. if (!buttonMeshName) {
  58968. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  58969. continue;
  58970. }
  58971. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  58972. if (!buttonMesh) {
  58973. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  58974. continue;
  58975. }
  58976. var buttonMeshInfo = {
  58977. index: i,
  58978. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  58979. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  58980. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  58981. };
  58982. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  58983. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  58984. }
  58985. else {
  58986. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  58987. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  58988. '(VALUE: ' + !!buttonMeshInfo.value +
  58989. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  58990. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  58991. ')');
  58992. }
  58993. }
  58994. // Axis Meshes
  58995. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  58996. var axisMeshName = this._mapping.axisMeshNames[i];
  58997. if (!axisMeshName) {
  58998. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  58999. continue;
  59000. }
  59001. var axisMesh = getChildByName(rootNode, axisMeshName);
  59002. if (!axisMesh) {
  59003. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  59004. continue;
  59005. }
  59006. var axisMeshInfo = {
  59007. index: i,
  59008. value: getImmediateChildByName(axisMesh, 'VALUE'),
  59009. min: getImmediateChildByName(axisMesh, 'MIN'),
  59010. max: getImmediateChildByName(axisMesh, 'MAX')
  59011. };
  59012. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  59013. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  59014. }
  59015. else {
  59016. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  59017. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  59018. '(VALUE: ' + !!axisMeshInfo.value +
  59019. ', MIN: ' + !!axisMeshInfo.min +
  59020. ', MAX:' + !!axisMeshInfo.max +
  59021. ')');
  59022. }
  59023. }
  59024. // Pointing Ray
  59025. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  59026. if (!loadedMeshInfo.pointingPoseNode) {
  59027. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  59028. }
  59029. return loadedMeshInfo;
  59030. // Look through all children recursively. This will return null if no mesh exists with the given name.
  59031. function getChildByName(node, name) {
  59032. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  59033. }
  59034. // Look through only immediate children. This will return null if no mesh exists with the given name.
  59035. function getImmediateChildByName(node, name) {
  59036. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  59037. }
  59038. };
  59039. WindowsMotionController.prototype.getForwardRay = function (length) {
  59040. if (length === void 0) { length = 100; }
  59041. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  59042. return _super.prototype.getForwardRay.call(this, length);
  59043. }
  59044. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  59045. var origin = m.getTranslation();
  59046. var forward = new BABYLON.Vector3(0, 0, -1);
  59047. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  59048. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  59049. return new BABYLON.Ray(origin, direction, length);
  59050. };
  59051. WindowsMotionController.prototype.dispose = function () {
  59052. _super.prototype.dispose.call(this);
  59053. this.onTrackpadChangedObservable.clear();
  59054. };
  59055. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  59056. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  59057. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  59058. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  59059. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  59060. return WindowsMotionController;
  59061. }(BABYLON.WebVRController));
  59062. BABYLON.WindowsMotionController = WindowsMotionController;
  59063. })(BABYLON || (BABYLON = {}));
  59064. //# sourceMappingURL=babylon.windowsMotionController.js.map
  59065. var BABYLON;
  59066. (function (BABYLON) {
  59067. var GearVRController = /** @class */ (function (_super) {
  59068. __extends(GearVRController, _super);
  59069. function GearVRController(vrGamepad) {
  59070. var _this = _super.call(this, vrGamepad) || this;
  59071. _this._buttonIndexToObservableNameMap = [
  59072. 'onTrackpadChangedObservable',
  59073. 'onTriggerStateChangedObservable' // Trigger
  59074. ];
  59075. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  59076. return _this;
  59077. }
  59078. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  59079. var _this = this;
  59080. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  59081. _this._defaultModel = newMeshes[1];
  59082. _this.attachToMesh(_this._defaultModel);
  59083. if (meshLoaded) {
  59084. meshLoaded(_this._defaultModel);
  59085. }
  59086. });
  59087. };
  59088. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  59089. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  59090. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  59091. // Only emit events for buttons that we know how to map from index to observable
  59092. var observable = this[observableName];
  59093. if (observable) {
  59094. observable.notifyObservers(state);
  59095. }
  59096. }
  59097. };
  59098. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  59099. GearVRController.MODEL_FILENAME = 'generic.babylon';
  59100. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  59101. return GearVRController;
  59102. }(BABYLON.WebVRController));
  59103. BABYLON.GearVRController = GearVRController;
  59104. })(BABYLON || (BABYLON = {}));
  59105. //# sourceMappingURL=babylon.gearVRController.js.map
  59106. var BABYLON;
  59107. (function (BABYLON) {
  59108. var FollowCamera = /** @class */ (function (_super) {
  59109. __extends(FollowCamera, _super);
  59110. function FollowCamera(name, position, scene, lockedTarget) {
  59111. if (lockedTarget === void 0) { lockedTarget = null; }
  59112. var _this = _super.call(this, name, position, scene) || this;
  59113. _this.radius = 12;
  59114. _this.rotationOffset = 0;
  59115. _this.heightOffset = 4;
  59116. _this.cameraAcceleration = 0.05;
  59117. _this.maxCameraSpeed = 20;
  59118. _this.lockedTarget = lockedTarget;
  59119. return _this;
  59120. }
  59121. FollowCamera.prototype.getRadians = function (degrees) {
  59122. return degrees * Math.PI / 180;
  59123. };
  59124. FollowCamera.prototype.follow = function (cameraTarget) {
  59125. if (!cameraTarget)
  59126. return;
  59127. var yRotation;
  59128. if (cameraTarget.rotationQuaternion) {
  59129. var rotMatrix = new BABYLON.Matrix();
  59130. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  59131. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  59132. }
  59133. else {
  59134. yRotation = cameraTarget.rotation.y;
  59135. }
  59136. var radians = this.getRadians(this.rotationOffset) + yRotation;
  59137. var targetPosition = cameraTarget.getAbsolutePosition();
  59138. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  59139. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  59140. var dx = targetX - this.position.x;
  59141. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  59142. var dz = (targetZ) - this.position.z;
  59143. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  59144. var vy = dy * this.cameraAcceleration;
  59145. var vz = dz * this.cameraAcceleration * 2;
  59146. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  59147. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59148. }
  59149. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  59150. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59151. }
  59152. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  59153. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59154. }
  59155. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  59156. this.setTarget(targetPosition);
  59157. };
  59158. FollowCamera.prototype._checkInputs = function () {
  59159. _super.prototype._checkInputs.call(this);
  59160. if (this.lockedTarget) {
  59161. this.follow(this.lockedTarget);
  59162. }
  59163. };
  59164. FollowCamera.prototype.getClassName = function () {
  59165. return "FollowCamera";
  59166. };
  59167. __decorate([
  59168. BABYLON.serialize()
  59169. ], FollowCamera.prototype, "radius", void 0);
  59170. __decorate([
  59171. BABYLON.serialize()
  59172. ], FollowCamera.prototype, "rotationOffset", void 0);
  59173. __decorate([
  59174. BABYLON.serialize()
  59175. ], FollowCamera.prototype, "heightOffset", void 0);
  59176. __decorate([
  59177. BABYLON.serialize()
  59178. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  59179. __decorate([
  59180. BABYLON.serialize()
  59181. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  59182. __decorate([
  59183. BABYLON.serializeAsMeshReference("lockedTargetId")
  59184. ], FollowCamera.prototype, "lockedTarget", void 0);
  59185. return FollowCamera;
  59186. }(BABYLON.TargetCamera));
  59187. BABYLON.FollowCamera = FollowCamera;
  59188. var ArcFollowCamera = /** @class */ (function (_super) {
  59189. __extends(ArcFollowCamera, _super);
  59190. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  59191. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  59192. _this.alpha = alpha;
  59193. _this.beta = beta;
  59194. _this.radius = radius;
  59195. _this.target = target;
  59196. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  59197. _this.follow();
  59198. return _this;
  59199. }
  59200. ArcFollowCamera.prototype.follow = function () {
  59201. if (!this.target) {
  59202. return;
  59203. }
  59204. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  59205. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  59206. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  59207. var targetPosition = this.target.getAbsolutePosition();
  59208. this.position = targetPosition.add(this._cartesianCoordinates);
  59209. this.setTarget(targetPosition);
  59210. };
  59211. ArcFollowCamera.prototype._checkInputs = function () {
  59212. _super.prototype._checkInputs.call(this);
  59213. this.follow();
  59214. };
  59215. ArcFollowCamera.prototype.getClassName = function () {
  59216. return "ArcFollowCamera";
  59217. };
  59218. return ArcFollowCamera;
  59219. }(BABYLON.TargetCamera));
  59220. BABYLON.ArcFollowCamera = ArcFollowCamera;
  59221. })(BABYLON || (BABYLON = {}));
  59222. //# sourceMappingURL=babylon.followCamera.js.map
  59223. var BABYLON;
  59224. (function (BABYLON) {
  59225. // We're mainly based on the logic defined into the FreeCamera code
  59226. var UniversalCamera = /** @class */ (function (_super) {
  59227. __extends(UniversalCamera, _super);
  59228. //-- end properties for backward compatibility for inputs
  59229. function UniversalCamera(name, position, scene) {
  59230. var _this = _super.call(this, name, position, scene) || this;
  59231. _this.inputs.addGamepad();
  59232. return _this;
  59233. }
  59234. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  59235. //-- Begin properties for backward compatibility for inputs
  59236. get: function () {
  59237. var gamepad = this.inputs.attached["gamepad"];
  59238. if (gamepad)
  59239. return gamepad.gamepadAngularSensibility;
  59240. return 0;
  59241. },
  59242. set: function (value) {
  59243. var gamepad = this.inputs.attached["gamepad"];
  59244. if (gamepad)
  59245. gamepad.gamepadAngularSensibility = value;
  59246. },
  59247. enumerable: true,
  59248. configurable: true
  59249. });
  59250. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  59251. get: function () {
  59252. var gamepad = this.inputs.attached["gamepad"];
  59253. if (gamepad)
  59254. return gamepad.gamepadMoveSensibility;
  59255. return 0;
  59256. },
  59257. set: function (value) {
  59258. var gamepad = this.inputs.attached["gamepad"];
  59259. if (gamepad)
  59260. gamepad.gamepadMoveSensibility = value;
  59261. },
  59262. enumerable: true,
  59263. configurable: true
  59264. });
  59265. UniversalCamera.prototype.getClassName = function () {
  59266. return "UniversalCamera";
  59267. };
  59268. return UniversalCamera;
  59269. }(BABYLON.TouchCamera));
  59270. BABYLON.UniversalCamera = UniversalCamera;
  59271. })(BABYLON || (BABYLON = {}));
  59272. //# sourceMappingURL=babylon.universalCamera.js.map
  59273. var BABYLON;
  59274. (function (BABYLON) {
  59275. // We're mainly based on the logic defined into the FreeCamera code
  59276. var GamepadCamera = /** @class */ (function (_super) {
  59277. __extends(GamepadCamera, _super);
  59278. //-- end properties for backward compatibility for inputs
  59279. function GamepadCamera(name, position, scene) {
  59280. return _super.call(this, name, position, scene) || this;
  59281. }
  59282. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  59283. //-- Begin properties for backward compatibility for inputs
  59284. get: function () {
  59285. var gamepad = this.inputs.attached["gamepad"];
  59286. if (gamepad)
  59287. return gamepad.gamepadAngularSensibility;
  59288. return 0;
  59289. },
  59290. set: function (value) {
  59291. var gamepad = this.inputs.attached["gamepad"];
  59292. if (gamepad)
  59293. gamepad.gamepadAngularSensibility = value;
  59294. },
  59295. enumerable: true,
  59296. configurable: true
  59297. });
  59298. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  59299. get: function () {
  59300. var gamepad = this.inputs.attached["gamepad"];
  59301. if (gamepad)
  59302. return gamepad.gamepadMoveSensibility;
  59303. return 0;
  59304. },
  59305. set: function (value) {
  59306. var gamepad = this.inputs.attached["gamepad"];
  59307. if (gamepad)
  59308. gamepad.gamepadMoveSensibility = value;
  59309. },
  59310. enumerable: true,
  59311. configurable: true
  59312. });
  59313. GamepadCamera.prototype.getClassName = function () {
  59314. return "GamepadCamera";
  59315. };
  59316. return GamepadCamera;
  59317. }(BABYLON.UniversalCamera));
  59318. BABYLON.GamepadCamera = GamepadCamera;
  59319. })(BABYLON || (BABYLON = {}));
  59320. //# sourceMappingURL=babylon.gamepadCamera.js.map
  59321. var BABYLON;
  59322. (function (BABYLON) {
  59323. var PostProcessRenderPipelineManager = /** @class */ (function () {
  59324. function PostProcessRenderPipelineManager() {
  59325. this._renderPipelines = {};
  59326. }
  59327. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  59328. this._renderPipelines[renderPipeline._name] = renderPipeline;
  59329. };
  59330. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  59331. if (unique === void 0) { unique = false; }
  59332. var renderPipeline = this._renderPipelines[renderPipelineName];
  59333. if (!renderPipeline) {
  59334. return;
  59335. }
  59336. renderPipeline._attachCameras(cameras, unique);
  59337. };
  59338. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  59339. var renderPipeline = this._renderPipelines[renderPipelineName];
  59340. if (!renderPipeline) {
  59341. return;
  59342. }
  59343. renderPipeline._detachCameras(cameras);
  59344. };
  59345. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  59346. var renderPipeline = this._renderPipelines[renderPipelineName];
  59347. if (!renderPipeline) {
  59348. return;
  59349. }
  59350. renderPipeline._enableEffect(renderEffectName, cameras);
  59351. };
  59352. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  59353. var renderPipeline = this._renderPipelines[renderPipelineName];
  59354. if (!renderPipeline) {
  59355. return;
  59356. }
  59357. renderPipeline._disableEffect(renderEffectName, cameras);
  59358. };
  59359. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  59360. var renderPipeline = this._renderPipelines[renderPipelineName];
  59361. if (!renderPipeline) {
  59362. return;
  59363. }
  59364. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  59365. };
  59366. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  59367. var renderPipeline = this._renderPipelines[renderPipelineName];
  59368. if (!renderPipeline) {
  59369. return;
  59370. }
  59371. renderPipeline._disableDisplayOnlyPass(cameras);
  59372. };
  59373. PostProcessRenderPipelineManager.prototype.update = function () {
  59374. for (var renderPipelineName in this._renderPipelines) {
  59375. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59376. var pipeline = this._renderPipelines[renderPipelineName];
  59377. if (!pipeline.isSupported) {
  59378. pipeline.dispose();
  59379. delete this._renderPipelines[renderPipelineName];
  59380. }
  59381. else {
  59382. pipeline._update();
  59383. }
  59384. }
  59385. }
  59386. };
  59387. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  59388. for (var renderPipelineName in this._renderPipelines) {
  59389. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59390. var pipeline = this._renderPipelines[renderPipelineName];
  59391. pipeline._rebuild();
  59392. }
  59393. }
  59394. };
  59395. PostProcessRenderPipelineManager.prototype.dispose = function () {
  59396. for (var renderPipelineName in this._renderPipelines) {
  59397. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59398. var pipeline = this._renderPipelines[renderPipelineName];
  59399. pipeline.dispose();
  59400. }
  59401. }
  59402. };
  59403. return PostProcessRenderPipelineManager;
  59404. }());
  59405. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  59406. })(BABYLON || (BABYLON = {}));
  59407. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  59408. var BABYLON;
  59409. (function (BABYLON) {
  59410. var PostProcessRenderPass = /** @class */ (function () {
  59411. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  59412. this._refCount = 0;
  59413. this._name = name;
  59414. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  59415. this.setRenderList(renderList);
  59416. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  59417. this._renderTexture.onAfterRenderObservable.add(afterRender);
  59418. this._scene = scene;
  59419. this._renderList = renderList;
  59420. }
  59421. // private
  59422. PostProcessRenderPass.prototype._incRefCount = function () {
  59423. if (this._refCount === 0) {
  59424. this._scene.customRenderTargets.push(this._renderTexture);
  59425. }
  59426. return ++this._refCount;
  59427. };
  59428. PostProcessRenderPass.prototype._decRefCount = function () {
  59429. this._refCount--;
  59430. if (this._refCount <= 0) {
  59431. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  59432. }
  59433. return this._refCount;
  59434. };
  59435. PostProcessRenderPass.prototype._update = function () {
  59436. this.setRenderList(this._renderList);
  59437. };
  59438. // public
  59439. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  59440. this._renderTexture.renderList = renderList;
  59441. };
  59442. PostProcessRenderPass.prototype.getRenderTexture = function () {
  59443. return this._renderTexture;
  59444. };
  59445. return PostProcessRenderPass;
  59446. }());
  59447. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  59448. })(BABYLON || (BABYLON = {}));
  59449. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  59450. var BABYLON;
  59451. (function (BABYLON) {
  59452. var PostProcessRenderEffect = /** @class */ (function () {
  59453. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  59454. this._name = name;
  59455. this._singleInstance = singleInstance || true;
  59456. this._getPostProcess = getPostProcess;
  59457. this._cameras = {};
  59458. this._indicesForCamera = {};
  59459. this._postProcesses = {};
  59460. this._renderPasses = {};
  59461. this._renderEffectAsPasses = {};
  59462. }
  59463. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  59464. get: function () {
  59465. for (var index in this._postProcesses) {
  59466. if (!this._postProcesses[index].isSupported) {
  59467. return false;
  59468. }
  59469. }
  59470. return true;
  59471. },
  59472. enumerable: true,
  59473. configurable: true
  59474. });
  59475. PostProcessRenderEffect.prototype._update = function () {
  59476. for (var renderPassName in this._renderPasses) {
  59477. this._renderPasses[renderPassName]._update();
  59478. }
  59479. };
  59480. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  59481. this._renderPasses[renderPass._name] = renderPass;
  59482. this._linkParameters();
  59483. };
  59484. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  59485. delete this._renderPasses[renderPass._name];
  59486. this._linkParameters();
  59487. };
  59488. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  59489. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  59490. this._linkParameters();
  59491. };
  59492. PostProcessRenderEffect.prototype.getPass = function (passName) {
  59493. for (var renderPassName in this._renderPasses) {
  59494. if (renderPassName === passName) {
  59495. return this._renderPasses[passName];
  59496. }
  59497. }
  59498. return null;
  59499. };
  59500. PostProcessRenderEffect.prototype.emptyPasses = function () {
  59501. this._renderPasses = {};
  59502. this._linkParameters();
  59503. };
  59504. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  59505. var cameraKey;
  59506. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59507. if (!cams) {
  59508. return;
  59509. }
  59510. for (var i = 0; i < cams.length; i++) {
  59511. var camera = cams[i];
  59512. var cameraName = camera.name;
  59513. if (this._singleInstance) {
  59514. cameraKey = 0;
  59515. }
  59516. else {
  59517. cameraKey = cameraName;
  59518. }
  59519. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  59520. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  59521. if (!this._indicesForCamera[cameraName]) {
  59522. this._indicesForCamera[cameraName] = [];
  59523. }
  59524. this._indicesForCamera[cameraName].push(index);
  59525. if (!this._cameras[cameraName]) {
  59526. this._cameras[cameraName] = camera;
  59527. }
  59528. for (var passName in this._renderPasses) {
  59529. this._renderPasses[passName]._incRefCount();
  59530. }
  59531. }
  59532. this._linkParameters();
  59533. };
  59534. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  59535. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59536. if (!cams) {
  59537. return;
  59538. }
  59539. for (var i = 0; i < cams.length; i++) {
  59540. var camera = cams[i];
  59541. var cameraName = camera.name;
  59542. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  59543. if (this._cameras[cameraName]) {
  59544. //this._indicesForCamera.splice(index, 1);
  59545. this._cameras[cameraName] = null;
  59546. }
  59547. for (var passName in this._renderPasses) {
  59548. this._renderPasses[passName]._decRefCount();
  59549. }
  59550. }
  59551. };
  59552. PostProcessRenderEffect.prototype._enable = function (cameras) {
  59553. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59554. if (!cams) {
  59555. return;
  59556. }
  59557. for (var i = 0; i < cams.length; i++) {
  59558. var camera = cams[i];
  59559. var cameraName = camera.name;
  59560. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  59561. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  59562. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  59563. }
  59564. }
  59565. for (var passName in this._renderPasses) {
  59566. this._renderPasses[passName]._incRefCount();
  59567. }
  59568. }
  59569. };
  59570. PostProcessRenderEffect.prototype._disable = function (cameras) {
  59571. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59572. if (!cams) {
  59573. return;
  59574. }
  59575. for (var i = 0; i < cams.length; i++) {
  59576. var camera = cams[i];
  59577. var cameraName = camera.Name;
  59578. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  59579. for (var passName in this._renderPasses) {
  59580. this._renderPasses[passName]._decRefCount();
  59581. }
  59582. }
  59583. };
  59584. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  59585. if (this._singleInstance) {
  59586. return this._postProcesses[0];
  59587. }
  59588. else {
  59589. if (!camera) {
  59590. return null;
  59591. }
  59592. return this._postProcesses[camera.name];
  59593. }
  59594. };
  59595. PostProcessRenderEffect.prototype._linkParameters = function () {
  59596. var _this = this;
  59597. for (var index in this._postProcesses) {
  59598. if (this.applyParameters) {
  59599. this.applyParameters(this._postProcesses[index]);
  59600. }
  59601. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  59602. _this._linkTextures(effect);
  59603. });
  59604. }
  59605. };
  59606. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  59607. for (var renderPassName in this._renderPasses) {
  59608. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  59609. }
  59610. for (var renderEffectName in this._renderEffectAsPasses) {
  59611. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  59612. }
  59613. };
  59614. return PostProcessRenderEffect;
  59615. }());
  59616. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  59617. })(BABYLON || (BABYLON = {}));
  59618. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  59619. var BABYLON;
  59620. (function (BABYLON) {
  59621. var PostProcessRenderPipeline = /** @class */ (function () {
  59622. function PostProcessRenderPipeline(engine, name) {
  59623. this._engine = engine;
  59624. this._name = name;
  59625. this._renderEffects = {};
  59626. this._renderEffectsForIsolatedPass = new Array();
  59627. this._cameras = [];
  59628. }
  59629. PostProcessRenderPipeline.prototype.getClassName = function () {
  59630. return "PostProcessRenderPipeline";
  59631. };
  59632. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  59633. get: function () {
  59634. for (var renderEffectName in this._renderEffects) {
  59635. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59636. if (!this._renderEffects[renderEffectName].isSupported) {
  59637. return false;
  59638. }
  59639. }
  59640. }
  59641. return true;
  59642. },
  59643. enumerable: true,
  59644. configurable: true
  59645. });
  59646. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  59647. this._renderEffects[renderEffect._name] = renderEffect;
  59648. };
  59649. // private
  59650. PostProcessRenderPipeline.prototype._rebuild = function () {
  59651. };
  59652. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  59653. var renderEffects = this._renderEffects[renderEffectName];
  59654. if (!renderEffects) {
  59655. return;
  59656. }
  59657. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  59658. };
  59659. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  59660. var renderEffects = this._renderEffects[renderEffectName];
  59661. if (!renderEffects) {
  59662. return;
  59663. }
  59664. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  59665. };
  59666. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  59667. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59668. if (!cams) {
  59669. return;
  59670. }
  59671. var indicesToDelete = [];
  59672. var i;
  59673. for (i = 0; i < cams.length; i++) {
  59674. var camera = cams[i];
  59675. var cameraName = camera.name;
  59676. if (this._cameras.indexOf(camera) === -1) {
  59677. this._cameras[cameraName] = camera;
  59678. }
  59679. else if (unique) {
  59680. indicesToDelete.push(i);
  59681. }
  59682. }
  59683. for (i = 0; i < indicesToDelete.length; i++) {
  59684. cameras.splice(indicesToDelete[i], 1);
  59685. }
  59686. for (var renderEffectName in this._renderEffects) {
  59687. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59688. this._renderEffects[renderEffectName]._attachCameras(cams);
  59689. }
  59690. }
  59691. };
  59692. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  59693. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59694. if (!cams) {
  59695. return;
  59696. }
  59697. for (var renderEffectName in this._renderEffects) {
  59698. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59699. this._renderEffects[renderEffectName]._detachCameras(cams);
  59700. }
  59701. }
  59702. for (var i = 0; i < cams.length; i++) {
  59703. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  59704. }
  59705. };
  59706. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  59707. var _this = this;
  59708. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59709. if (!cams) {
  59710. return;
  59711. }
  59712. var pass = null;
  59713. var renderEffectName;
  59714. for (renderEffectName in this._renderEffects) {
  59715. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59716. pass = this._renderEffects[renderEffectName].getPass(passName);
  59717. if (pass != null) {
  59718. break;
  59719. }
  59720. }
  59721. }
  59722. if (pass === null) {
  59723. return;
  59724. }
  59725. for (renderEffectName in this._renderEffects) {
  59726. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59727. this._renderEffects[renderEffectName]._disable(cams);
  59728. }
  59729. }
  59730. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  59731. for (var i = 0; i < cams.length; i++) {
  59732. var camera = cams[i];
  59733. var cameraName = camera.name;
  59734. 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); });
  59735. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  59736. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  59737. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  59738. }
  59739. };
  59740. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  59741. var _this = this;
  59742. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59743. if (!cams) {
  59744. return;
  59745. }
  59746. for (var i = 0; i < cams.length; i++) {
  59747. var camera = cams[i];
  59748. var cameraName = camera.name;
  59749. 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); });
  59750. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  59751. }
  59752. for (var renderEffectName in this._renderEffects) {
  59753. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59754. this._renderEffects[renderEffectName]._enable(cams);
  59755. }
  59756. }
  59757. };
  59758. PostProcessRenderPipeline.prototype._update = function () {
  59759. for (var renderEffectName in this._renderEffects) {
  59760. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59761. this._renderEffects[renderEffectName]._update();
  59762. }
  59763. }
  59764. for (var i = 0; i < this._cameras.length; i++) {
  59765. var cameraName = this._cameras[i].name;
  59766. if (this._renderEffectsForIsolatedPass[cameraName]) {
  59767. this._renderEffectsForIsolatedPass[cameraName]._update();
  59768. }
  59769. }
  59770. };
  59771. PostProcessRenderPipeline.prototype._reset = function () {
  59772. this._renderEffects = {};
  59773. this._renderEffectsForIsolatedPass = new Array();
  59774. };
  59775. PostProcessRenderPipeline.prototype.dispose = function () {
  59776. // Must be implemented by children
  59777. };
  59778. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  59779. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  59780. __decorate([
  59781. BABYLON.serialize()
  59782. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  59783. return PostProcessRenderPipeline;
  59784. }());
  59785. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  59786. })(BABYLON || (BABYLON = {}));
  59787. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  59788. var BABYLON;
  59789. (function (BABYLON) {
  59790. var DepthRenderer = /** @class */ (function () {
  59791. function DepthRenderer(scene, type) {
  59792. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  59793. var _this = this;
  59794. this._scene = scene;
  59795. var engine = scene.getEngine();
  59796. // Render target
  59797. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  59798. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59799. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59800. this._depthMap.refreshRate = 1;
  59801. this._depthMap.renderParticles = false;
  59802. this._depthMap.renderList = null;
  59803. // set default depth value to 1.0 (far away)
  59804. this._depthMap.onClearObservable.add(function (engine) {
  59805. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59806. });
  59807. // Custom render function
  59808. var renderSubMesh = function (subMesh) {
  59809. var mesh = subMesh.getRenderingMesh();
  59810. var scene = _this._scene;
  59811. var engine = scene.getEngine();
  59812. var material = subMesh.getMaterial();
  59813. if (!material) {
  59814. return;
  59815. }
  59816. // Culling and reverse (right handed system)
  59817. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  59818. // Managing instances
  59819. var batch = mesh._getInstancesRenderList(subMesh._id);
  59820. if (batch.mustReturn) {
  59821. return;
  59822. }
  59823. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59824. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  59825. engine.enableEffect(_this._effect);
  59826. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59827. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59828. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  59829. // Alpha test
  59830. if (material && material.needAlphaTesting()) {
  59831. var alphaTexture = material.getAlphaTestTexture();
  59832. if (alphaTexture) {
  59833. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59834. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59835. }
  59836. }
  59837. // Bones
  59838. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59839. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59840. }
  59841. // Draw
  59842. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59843. }
  59844. };
  59845. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59846. var index;
  59847. if (depthOnlySubMeshes.length) {
  59848. engine.setColorWrite(false);
  59849. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59850. renderSubMesh(depthOnlySubMeshes.data[index]);
  59851. }
  59852. engine.setColorWrite(true);
  59853. }
  59854. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59855. renderSubMesh(opaqueSubMeshes.data[index]);
  59856. }
  59857. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59858. renderSubMesh(alphaTestSubMeshes.data[index]);
  59859. }
  59860. };
  59861. }
  59862. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  59863. var material = subMesh.getMaterial();
  59864. if (material.disableDepthWrite) {
  59865. return false;
  59866. }
  59867. var defines = [];
  59868. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59869. var mesh = subMesh.getMesh();
  59870. // Alpha test
  59871. if (material && material.needAlphaTesting()) {
  59872. defines.push("#define ALPHATEST");
  59873. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59874. attribs.push(BABYLON.VertexBuffer.UVKind);
  59875. defines.push("#define UV1");
  59876. }
  59877. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59878. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59879. defines.push("#define UV2");
  59880. }
  59881. }
  59882. // Bones
  59883. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59884. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59885. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59886. if (mesh.numBoneInfluencers > 4) {
  59887. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59888. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59889. }
  59890. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59891. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  59892. }
  59893. else {
  59894. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59895. }
  59896. // Instances
  59897. if (useInstances) {
  59898. defines.push("#define INSTANCES");
  59899. attribs.push("world0");
  59900. attribs.push("world1");
  59901. attribs.push("world2");
  59902. attribs.push("world3");
  59903. }
  59904. // Get correct effect
  59905. var join = defines.join("\n");
  59906. if (this._cachedDefines !== join) {
  59907. this._cachedDefines = join;
  59908. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  59909. }
  59910. return this._effect.isReady();
  59911. };
  59912. DepthRenderer.prototype.getDepthMap = function () {
  59913. return this._depthMap;
  59914. };
  59915. // Methods
  59916. DepthRenderer.prototype.dispose = function () {
  59917. this._depthMap.dispose();
  59918. };
  59919. return DepthRenderer;
  59920. }());
  59921. BABYLON.DepthRenderer = DepthRenderer;
  59922. })(BABYLON || (BABYLON = {}));
  59923. //# sourceMappingURL=babylon.depthRenderer.js.map
  59924. var BABYLON;
  59925. (function (BABYLON) {
  59926. var SSAORenderingPipeline = /** @class */ (function (_super) {
  59927. __extends(SSAORenderingPipeline, _super);
  59928. /**
  59929. * @constructor
  59930. * @param {string} name - The rendering pipeline name
  59931. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59932. * @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 }
  59933. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59934. */
  59935. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  59936. var _this = _super.call(this, scene.getEngine(), name) || this;
  59937. // Members
  59938. /**
  59939. * The PassPostProcess id in the pipeline that contains the original scene color
  59940. * @type {string}
  59941. */
  59942. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  59943. /**
  59944. * The SSAO PostProcess id in the pipeline
  59945. * @type {string}
  59946. */
  59947. _this.SSAORenderEffect = "SSAORenderEffect";
  59948. /**
  59949. * The horizontal blur PostProcess id in the pipeline
  59950. * @type {string}
  59951. */
  59952. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  59953. /**
  59954. * The vertical blur PostProcess id in the pipeline
  59955. * @type {string}
  59956. */
  59957. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  59958. /**
  59959. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  59960. * @type {string}
  59961. */
  59962. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  59963. /**
  59964. * The output strength of the SSAO post-process. Default value is 1.0.
  59965. * @type {number}
  59966. */
  59967. _this.totalStrength = 1.0;
  59968. /**
  59969. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  59970. * @type {number}
  59971. */
  59972. _this.radius = 0.0001;
  59973. /**
  59974. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  59975. * Must not be equal to fallOff and superior to fallOff.
  59976. * Default value is 0.975
  59977. * @type {number}
  59978. */
  59979. _this.area = 0.0075;
  59980. /**
  59981. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  59982. * Must not be equal to area and inferior to area.
  59983. * Default value is 0.0
  59984. * @type {number}
  59985. */
  59986. _this.fallOff = 0.000001;
  59987. /**
  59988. * The base color of the SSAO post-process
  59989. * The final result is "base + ssao" between [0, 1]
  59990. * @type {number}
  59991. */
  59992. _this.base = 0.5;
  59993. _this._firstUpdate = true;
  59994. _this._scene = scene;
  59995. // Set up assets
  59996. _this._createRandomTexture();
  59997. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  59998. var ssaoRatio = ratio.ssaoRatio || ratio;
  59999. var combineRatio = ratio.combineRatio || ratio;
  60000. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  60001. _this._createSSAOPostProcess(ssaoRatio);
  60002. _this._createBlurPostProcess(ssaoRatio);
  60003. _this._createSSAOCombinePostProcess(combineRatio);
  60004. // Set up pipeline
  60005. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  60006. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  60007. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  60008. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  60009. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  60010. // Finish
  60011. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60012. if (cameras)
  60013. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60014. return _this;
  60015. }
  60016. // Public Methods
  60017. /**
  60018. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  60019. */
  60020. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  60021. if (disableDepthRender === void 0) { disableDepthRender = false; }
  60022. for (var i = 0; i < this._scene.cameras.length; i++) {
  60023. var camera = this._scene.cameras[i];
  60024. this._originalColorPostProcess.dispose(camera);
  60025. this._ssaoPostProcess.dispose(camera);
  60026. this._blurHPostProcess.dispose(camera);
  60027. this._blurVPostProcess.dispose(camera);
  60028. this._ssaoCombinePostProcess.dispose(camera);
  60029. }
  60030. this._randomTexture.dispose();
  60031. if (disableDepthRender)
  60032. this._scene.disableDepthRenderer();
  60033. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60034. _super.prototype.dispose.call(this);
  60035. };
  60036. // Private Methods
  60037. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  60038. var _this = this;
  60039. var size = 16;
  60040. 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);
  60041. 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);
  60042. this._blurHPostProcess.onActivateObservable.add(function () {
  60043. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  60044. _this._blurHPostProcess.kernel = size * dw;
  60045. });
  60046. this._blurVPostProcess.onActivateObservable.add(function () {
  60047. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  60048. _this._blurVPostProcess.kernel = size * dw;
  60049. });
  60050. };
  60051. SSAORenderingPipeline.prototype._rebuild = function () {
  60052. this._firstUpdate = true;
  60053. _super.prototype._rebuild.call(this);
  60054. };
  60055. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  60056. var _this = this;
  60057. var numSamples = 16;
  60058. var sampleSphere = [
  60059. 0.5381, 0.1856, -0.4319,
  60060. 0.1379, 0.2486, 0.4430,
  60061. 0.3371, 0.5679, -0.0057,
  60062. -0.6999, -0.0451, -0.0019,
  60063. 0.0689, -0.1598, -0.8547,
  60064. 0.0560, 0.0069, -0.1843,
  60065. -0.0146, 0.1402, 0.0762,
  60066. 0.0100, -0.1924, -0.0344,
  60067. -0.3577, -0.5301, -0.4358,
  60068. -0.3169, 0.1063, 0.0158,
  60069. 0.0103, -0.5869, 0.0046,
  60070. -0.0897, -0.4940, 0.3287,
  60071. 0.7119, -0.0154, -0.0918,
  60072. -0.0533, 0.0596, -0.5411,
  60073. 0.0352, -0.0631, 0.5460,
  60074. -0.4776, 0.2847, -0.0271
  60075. ];
  60076. var samplesFactor = 1.0 / numSamples;
  60077. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  60078. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  60079. "area", "fallOff", "base", "range", "viewport"
  60080. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  60081. this._ssaoPostProcess.onApply = function (effect) {
  60082. if (_this._firstUpdate) {
  60083. effect.setArray3("sampleSphere", sampleSphere);
  60084. effect.setFloat("samplesFactor", samplesFactor);
  60085. effect.setFloat("randTextureTiles", 4.0);
  60086. }
  60087. effect.setFloat("totalStrength", _this.totalStrength);
  60088. effect.setFloat("radius", _this.radius);
  60089. effect.setFloat("area", _this.area);
  60090. effect.setFloat("fallOff", _this.fallOff);
  60091. effect.setFloat("base", _this.base);
  60092. effect.setTexture("textureSampler", _this._depthTexture);
  60093. effect.setTexture("randomSampler", _this._randomTexture);
  60094. };
  60095. };
  60096. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  60097. var _this = this;
  60098. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60099. this._ssaoCombinePostProcess.onApply = function (effect) {
  60100. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  60101. };
  60102. };
  60103. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  60104. var size = 512;
  60105. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60106. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60107. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60108. var context = this._randomTexture.getContext();
  60109. var rand = function (min, max) {
  60110. return Math.random() * (max - min) + min;
  60111. };
  60112. var randVector = BABYLON.Vector3.Zero();
  60113. for (var x = 0; x < size; x++) {
  60114. for (var y = 0; y < size; y++) {
  60115. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  60116. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  60117. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  60118. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  60119. context.fillRect(x, y, 1, 1);
  60120. }
  60121. }
  60122. this._randomTexture.update(false);
  60123. };
  60124. __decorate([
  60125. BABYLON.serialize()
  60126. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  60127. __decorate([
  60128. BABYLON.serialize()
  60129. ], SSAORenderingPipeline.prototype, "radius", void 0);
  60130. __decorate([
  60131. BABYLON.serialize()
  60132. ], SSAORenderingPipeline.prototype, "area", void 0);
  60133. __decorate([
  60134. BABYLON.serialize()
  60135. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  60136. __decorate([
  60137. BABYLON.serialize()
  60138. ], SSAORenderingPipeline.prototype, "base", void 0);
  60139. return SSAORenderingPipeline;
  60140. }(BABYLON.PostProcessRenderPipeline));
  60141. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  60142. })(BABYLON || (BABYLON = {}));
  60143. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  60144. var BABYLON;
  60145. (function (BABYLON) {
  60146. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  60147. __extends(SSAO2RenderingPipeline, _super);
  60148. /**
  60149. * @constructor
  60150. * @param {string} name - The rendering pipeline name
  60151. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60152. * @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 }
  60153. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60154. */
  60155. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  60156. var _this = _super.call(this, scene.getEngine(), name) || this;
  60157. // Members
  60158. /**
  60159. * The PassPostProcess id in the pipeline that contains the original scene color
  60160. * @type {string}
  60161. */
  60162. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  60163. /**
  60164. * The SSAO PostProcess id in the pipeline
  60165. * @type {string}
  60166. */
  60167. _this.SSAORenderEffect = "SSAORenderEffect";
  60168. /**
  60169. * The horizontal blur PostProcess id in the pipeline
  60170. * @type {string}
  60171. */
  60172. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  60173. /**
  60174. * The vertical blur PostProcess id in the pipeline
  60175. * @type {string}
  60176. */
  60177. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  60178. /**
  60179. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  60180. * @type {string}
  60181. */
  60182. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  60183. /**
  60184. * The output strength of the SSAO post-process. Default value is 1.0.
  60185. * @type {number}
  60186. */
  60187. _this.totalStrength = 1.0;
  60188. /**
  60189. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  60190. * @type {number}
  60191. */
  60192. _this.maxZ = 100.0;
  60193. /**
  60194. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  60195. * @type {number}
  60196. */
  60197. _this.minZAspect = 0.2;
  60198. /**
  60199. * Number of samples used for the SSAO calculations. Default value is 8
  60200. * @type {number}
  60201. */
  60202. _this._samples = 8;
  60203. /**
  60204. * Are we using bilateral blur ?
  60205. * @type {boolean}
  60206. */
  60207. _this._expensiveBlur = true;
  60208. /**
  60209. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  60210. * @type {number}
  60211. */
  60212. _this.radius = 2.0;
  60213. /**
  60214. * The base color of the SSAO post-process
  60215. * The final result is "base + ssao" between [0, 1]
  60216. * @type {number}
  60217. */
  60218. _this.base = 0.1;
  60219. _this._firstUpdate = true;
  60220. _this._scene = scene;
  60221. if (!_this.isSupported) {
  60222. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  60223. return _this;
  60224. }
  60225. var ssaoRatio = ratio.ssaoRatio || ratio;
  60226. var blurRatio = ratio.blurRatio || ratio;
  60227. // Set up assets
  60228. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  60229. _this._createRandomTexture();
  60230. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  60231. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  60232. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  60233. _this._createSSAOPostProcess(1.0);
  60234. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  60235. _this._createSSAOCombinePostProcess(blurRatio);
  60236. // Set up pipeline
  60237. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  60238. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  60239. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  60240. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  60241. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  60242. // Finish
  60243. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60244. if (cameras)
  60245. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60246. return _this;
  60247. }
  60248. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  60249. get: function () {
  60250. return this._samples;
  60251. },
  60252. set: function (n) {
  60253. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  60254. this._samples = n;
  60255. this._sampleSphere = this._generateHemisphere();
  60256. this._firstUpdate = true;
  60257. },
  60258. enumerable: true,
  60259. configurable: true
  60260. });
  60261. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  60262. get: function () {
  60263. return this._expensiveBlur;
  60264. },
  60265. set: function (b) {
  60266. 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"]);
  60267. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  60268. this._expensiveBlur = b;
  60269. this._firstUpdate = true;
  60270. },
  60271. enumerable: true,
  60272. configurable: true
  60273. });
  60274. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  60275. /**
  60276. * Support test.
  60277. * @type {boolean}
  60278. */
  60279. get: function () {
  60280. var engine = BABYLON.Engine.LastCreatedEngine;
  60281. if (!engine) {
  60282. return false;
  60283. }
  60284. return engine.getCaps().drawBuffersExtension;
  60285. },
  60286. enumerable: true,
  60287. configurable: true
  60288. });
  60289. // Public Methods
  60290. /**
  60291. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  60292. */
  60293. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  60294. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  60295. for (var i = 0; i < this._scene.cameras.length; i++) {
  60296. var camera = this._scene.cameras[i];
  60297. this._originalColorPostProcess.dispose(camera);
  60298. this._ssaoPostProcess.dispose(camera);
  60299. this._blurHPostProcess.dispose(camera);
  60300. this._blurVPostProcess.dispose(camera);
  60301. this._ssaoCombinePostProcess.dispose(camera);
  60302. }
  60303. this._randomTexture.dispose();
  60304. if (disableGeometryBufferRenderer)
  60305. this._scene.disableGeometryBufferRenderer();
  60306. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60307. _super.prototype.dispose.call(this);
  60308. };
  60309. // Private Methods
  60310. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  60311. var _this = this;
  60312. this._samplerOffsets = [];
  60313. var expensive = this.expensiveBlur;
  60314. for (var i = -8; i < 8; i++) {
  60315. this._samplerOffsets.push(i * 2 + 0.5);
  60316. }
  60317. 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");
  60318. this._blurHPostProcess.onApply = function (effect) {
  60319. if (!_this._scene.activeCamera) {
  60320. return;
  60321. }
  60322. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  60323. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60324. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60325. effect.setFloat("radius", _this.radius);
  60326. effect.setTexture("depthSampler", _this._depthTexture);
  60327. if (_this._firstUpdate) {
  60328. effect.setArray("samplerOffsets", _this._samplerOffsets);
  60329. }
  60330. };
  60331. 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");
  60332. this._blurVPostProcess.onApply = function (effect) {
  60333. if (!_this._scene.activeCamera) {
  60334. return;
  60335. }
  60336. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  60337. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60338. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60339. effect.setFloat("radius", _this.radius);
  60340. effect.setTexture("depthSampler", _this._depthTexture);
  60341. if (_this._firstUpdate) {
  60342. effect.setArray("samplerOffsets", _this._samplerOffsets);
  60343. _this._firstUpdate = false;
  60344. }
  60345. };
  60346. };
  60347. SSAO2RenderingPipeline.prototype._rebuild = function () {
  60348. this._firstUpdate = true;
  60349. _super.prototype._rebuild.call(this);
  60350. };
  60351. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  60352. var numSamples = this.samples;
  60353. var result = [];
  60354. var vector, scale;
  60355. var rand = function (min, max) {
  60356. return Math.random() * (max - min) + min;
  60357. };
  60358. var i = 0;
  60359. while (i < numSamples) {
  60360. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  60361. vector.normalize();
  60362. scale = i / numSamples;
  60363. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  60364. vector.scaleInPlace(scale);
  60365. result.push(vector.x, vector.y, vector.z);
  60366. i++;
  60367. }
  60368. return result;
  60369. };
  60370. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  60371. var _this = this;
  60372. var numSamples = this.samples;
  60373. this._sampleSphere = this._generateHemisphere();
  60374. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  60375. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  60376. "base", "range", "projection", "near", "far", "texelSize",
  60377. "xViewport", "yViewport", "maxZ", "minZAspect"
  60378. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  60379. this._ssaoPostProcess.onApply = function (effect) {
  60380. if (_this._firstUpdate) {
  60381. effect.setArray3("sampleSphere", _this._sampleSphere);
  60382. effect.setFloat("randTextureTiles", 4.0);
  60383. }
  60384. if (!_this._scene.activeCamera) {
  60385. return;
  60386. }
  60387. effect.setFloat("samplesFactor", 1 / _this.samples);
  60388. effect.setFloat("totalStrength", _this.totalStrength);
  60389. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  60390. effect.setFloat("radius", _this.radius);
  60391. effect.setFloat("maxZ", _this.maxZ);
  60392. effect.setFloat("minZAspect", _this.minZAspect);
  60393. effect.setFloat("base", _this.base);
  60394. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60395. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60396. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  60397. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  60398. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  60399. effect.setTexture("textureSampler", _this._depthTexture);
  60400. effect.setTexture("normalSampler", _this._normalTexture);
  60401. effect.setTexture("randomSampler", _this._randomTexture);
  60402. };
  60403. };
  60404. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  60405. var _this = this;
  60406. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60407. this._ssaoCombinePostProcess.onApply = function (effect) {
  60408. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  60409. };
  60410. };
  60411. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  60412. var size = 512;
  60413. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60414. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60415. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60416. var context = this._randomTexture.getContext();
  60417. var rand = function (min, max) {
  60418. return Math.random() * (max - min) + min;
  60419. };
  60420. var randVector = BABYLON.Vector3.Zero();
  60421. for (var x = 0; x < size; x++) {
  60422. for (var y = 0; y < size; y++) {
  60423. randVector.x = rand(0.0, 1.0);
  60424. randVector.y = rand(0.0, 1.0);
  60425. randVector.z = 0.0;
  60426. randVector.normalize();
  60427. randVector.scaleInPlace(255);
  60428. randVector.x = Math.floor(randVector.x);
  60429. randVector.y = Math.floor(randVector.y);
  60430. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  60431. context.fillRect(x, y, 1, 1);
  60432. }
  60433. }
  60434. this._randomTexture.update(false);
  60435. };
  60436. __decorate([
  60437. BABYLON.serialize()
  60438. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  60439. __decorate([
  60440. BABYLON.serialize()
  60441. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  60442. __decorate([
  60443. BABYLON.serialize()
  60444. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  60445. __decorate([
  60446. BABYLON.serialize("samples")
  60447. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  60448. __decorate([
  60449. BABYLON.serialize("expensiveBlur")
  60450. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  60451. __decorate([
  60452. BABYLON.serialize()
  60453. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  60454. __decorate([
  60455. BABYLON.serialize()
  60456. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  60457. return SSAO2RenderingPipeline;
  60458. }(BABYLON.PostProcessRenderPipeline));
  60459. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  60460. })(BABYLON || (BABYLON = {}));
  60461. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  60462. // BABYLON.JS Chromatic Aberration GLSL Shader
  60463. // Author: Olivier Guyot
  60464. // Separates very slightly R, G and B colors on the edges of the screen
  60465. // Inspired by Francois Tarlier & Martins Upitis
  60466. var BABYLON;
  60467. (function (BABYLON) {
  60468. var LensRenderingPipeline = /** @class */ (function (_super) {
  60469. __extends(LensRenderingPipeline, _super);
  60470. /**
  60471. * @constructor
  60472. *
  60473. * Effect parameters are as follow:
  60474. * {
  60475. * chromatic_aberration: number; // from 0 to x (1 for realism)
  60476. * edge_blur: number; // from 0 to x (1 for realism)
  60477. * distortion: number; // from 0 to x (1 for realism)
  60478. * grain_amount: number; // from 0 to 1
  60479. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  60480. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  60481. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  60482. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  60483. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  60484. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  60485. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  60486. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  60487. * }
  60488. * Note: if an effect parameter is unset, effect is disabled
  60489. *
  60490. * @param {string} name - The rendering pipeline name
  60491. * @param {object} parameters - An object containing all parameters (see above)
  60492. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60493. * @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)
  60494. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60495. */
  60496. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  60497. if (ratio === void 0) { ratio = 1.0; }
  60498. var _this = _super.call(this, scene.getEngine(), name) || this;
  60499. // Lens effects can be of the following:
  60500. // - chromatic aberration (slight shift of RGB colors)
  60501. // - blur on the edge of the lens
  60502. // - lens distortion
  60503. // - depth-of-field blur & highlights enhancing
  60504. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  60505. // - grain effect (noise or custom texture)
  60506. // Two additional texture samplers are needed:
  60507. // - depth map (for depth-of-field)
  60508. // - grain texture
  60509. /**
  60510. * The chromatic aberration PostProcess id in the pipeline
  60511. * @type {string}
  60512. */
  60513. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  60514. /**
  60515. * The highlights enhancing PostProcess id in the pipeline
  60516. * @type {string}
  60517. */
  60518. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  60519. /**
  60520. * The depth-of-field PostProcess id in the pipeline
  60521. * @type {string}
  60522. */
  60523. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  60524. _this._scene = scene;
  60525. // Fetch texture samplers
  60526. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  60527. if (parameters.grain_texture) {
  60528. _this._grainTexture = parameters.grain_texture;
  60529. }
  60530. else {
  60531. _this._createGrainTexture();
  60532. }
  60533. // save parameters
  60534. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  60535. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  60536. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  60537. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  60538. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  60539. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  60540. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  60541. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  60542. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  60543. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  60544. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  60545. // Create effects
  60546. _this._createChromaticAberrationPostProcess(ratio);
  60547. _this._createHighlightsPostProcess(ratio);
  60548. _this._createDepthOfFieldPostProcess(ratio / 4);
  60549. // Set up pipeline
  60550. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  60551. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  60552. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  60553. if (_this._highlightsGain === -1) {
  60554. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  60555. }
  60556. // Finish
  60557. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60558. if (cameras) {
  60559. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60560. }
  60561. return _this;
  60562. }
  60563. // public methods (self explanatory)
  60564. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  60565. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  60566. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  60567. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  60568. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  60569. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  60570. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  60571. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  60572. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  60573. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  60574. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  60575. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  60576. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  60577. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  60578. };
  60579. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  60580. this._highlightsPostProcess.updateEffect();
  60581. };
  60582. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  60583. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  60584. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  60585. this._highlightsGain = amount;
  60586. };
  60587. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  60588. if (this._highlightsGain === -1) {
  60589. this._highlightsGain = 1.0;
  60590. }
  60591. this._highlightsThreshold = amount;
  60592. };
  60593. LensRenderingPipeline.prototype.disableHighlights = function () {
  60594. this._highlightsGain = -1;
  60595. };
  60596. /**
  60597. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  60598. */
  60599. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  60600. if (disableDepthRender === void 0) { disableDepthRender = false; }
  60601. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60602. this._chromaticAberrationPostProcess = null;
  60603. this._highlightsPostProcess = null;
  60604. this._depthOfFieldPostProcess = null;
  60605. this._grainTexture.dispose();
  60606. if (disableDepthRender)
  60607. this._scene.disableDepthRenderer();
  60608. };
  60609. // colors shifting and distortion
  60610. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  60611. var _this = this;
  60612. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  60613. [], // samplers
  60614. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60615. this._chromaticAberrationPostProcess.onApply = function (effect) {
  60616. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  60617. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60618. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60619. };
  60620. };
  60621. // highlights enhancing
  60622. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  60623. var _this = this;
  60624. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  60625. [], // samplers
  60626. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  60627. this._highlightsPostProcess.onApply = function (effect) {
  60628. effect.setFloat('gain', _this._highlightsGain);
  60629. effect.setFloat('threshold', _this._highlightsThreshold);
  60630. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  60631. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60632. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60633. };
  60634. };
  60635. // colors shifting and distortion
  60636. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  60637. var _this = this;
  60638. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  60639. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  60640. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  60641. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60642. this._depthOfFieldPostProcess.onApply = function (effect) {
  60643. effect.setTexture("depthSampler", _this._depthTexture);
  60644. effect.setTexture("grainSampler", _this._grainTexture);
  60645. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  60646. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  60647. effect.setFloat('grain_amount', _this._grainAmount);
  60648. effect.setBool('blur_noise', _this._blurNoise);
  60649. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60650. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60651. effect.setFloat('distortion', _this._distortion);
  60652. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  60653. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  60654. effect.setFloat('aperture', _this._dofAperture);
  60655. effect.setFloat('darken', _this._dofDarken);
  60656. effect.setFloat('edge_blur', _this._edgeBlur);
  60657. effect.setBool('highlights', (_this._highlightsGain !== -1));
  60658. if (_this._scene.activeCamera) {
  60659. effect.setFloat('near', _this._scene.activeCamera.minZ);
  60660. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  60661. }
  60662. };
  60663. };
  60664. // creates a black and white random noise texture, 512x512
  60665. LensRenderingPipeline.prototype._createGrainTexture = function () {
  60666. var size = 512;
  60667. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60668. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60669. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60670. var context = this._grainTexture.getContext();
  60671. var rand = function (min, max) {
  60672. return Math.random() * (max - min) + min;
  60673. };
  60674. var value;
  60675. for (var x = 0; x < size; x++) {
  60676. for (var y = 0; y < size; y++) {
  60677. value = Math.floor(rand(0.42, 0.58) * 255);
  60678. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  60679. context.fillRect(x, y, 1, 1);
  60680. }
  60681. }
  60682. this._grainTexture.update(false);
  60683. };
  60684. return LensRenderingPipeline;
  60685. }(BABYLON.PostProcessRenderPipeline));
  60686. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  60687. })(BABYLON || (BABYLON = {}));
  60688. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  60689. var BABYLON;
  60690. (function (BABYLON) {
  60691. var StandardRenderingPipeline = /** @class */ (function (_super) {
  60692. __extends(StandardRenderingPipeline, _super);
  60693. /**
  60694. * @constructor
  60695. * @param {string} name - The rendering pipeline name
  60696. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60697. * @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)
  60698. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  60699. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60700. */
  60701. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  60702. if (originalPostProcess === void 0) { originalPostProcess = null; }
  60703. var _this = _super.call(this, scene.getEngine(), name) || this;
  60704. _this.downSampleX4PostProcess = null;
  60705. _this.brightPassPostProcess = null;
  60706. _this.blurHPostProcesses = [];
  60707. _this.blurVPostProcesses = [];
  60708. _this.textureAdderPostProcess = null;
  60709. _this.volumetricLightPostProcess = null;
  60710. _this.volumetricLightSmoothXPostProcess = null;
  60711. _this.volumetricLightSmoothYPostProcess = null;
  60712. _this.volumetricLightMergePostProces = null;
  60713. _this.volumetricLightFinalPostProcess = null;
  60714. _this.luminancePostProcess = null;
  60715. _this.luminanceDownSamplePostProcesses = [];
  60716. _this.hdrPostProcess = null;
  60717. _this.textureAdderFinalPostProcess = null;
  60718. _this.lensFlareFinalPostProcess = null;
  60719. _this.hdrFinalPostProcess = null;
  60720. _this.lensFlarePostProcess = null;
  60721. _this.lensFlareComposePostProcess = null;
  60722. _this.motionBlurPostProcess = null;
  60723. _this.depthOfFieldPostProcess = null;
  60724. // Values
  60725. _this.brightThreshold = 1.0;
  60726. _this.blurWidth = 512.0;
  60727. _this.horizontalBlur = false;
  60728. _this.exposure = 1.0;
  60729. _this.lensTexture = null;
  60730. _this.volumetricLightCoefficient = 0.2;
  60731. _this.volumetricLightPower = 4.0;
  60732. _this.volumetricLightBlurScale = 64.0;
  60733. _this.sourceLight = null;
  60734. _this.hdrMinimumLuminance = 1.0;
  60735. _this.hdrDecreaseRate = 0.5;
  60736. _this.hdrIncreaseRate = 0.5;
  60737. _this.lensColorTexture = null;
  60738. _this.lensFlareStrength = 20.0;
  60739. _this.lensFlareGhostDispersal = 1.4;
  60740. _this.lensFlareHaloWidth = 0.7;
  60741. _this.lensFlareDistortionStrength = 16.0;
  60742. _this.lensStarTexture = null;
  60743. _this.lensFlareDirtTexture = null;
  60744. _this.depthOfFieldDistance = 10.0;
  60745. _this.depthOfFieldBlurWidth = 64.0;
  60746. _this.motionStrength = 1.0;
  60747. // IAnimatable
  60748. _this.animations = [];
  60749. _this._currentDepthOfFieldSource = null;
  60750. _this._hdrCurrentLuminance = 1.0;
  60751. // Getters and setters
  60752. _this._bloomEnabled = true;
  60753. _this._depthOfFieldEnabled = false;
  60754. _this._vlsEnabled = false;
  60755. _this._lensFlareEnabled = false;
  60756. _this._hdrEnabled = false;
  60757. _this._motionBlurEnabled = false;
  60758. _this._motionBlurSamples = 64.0;
  60759. _this._volumetricLightStepsCount = 50.0;
  60760. _this._cameras = cameras || [];
  60761. // Initialize
  60762. _this._scene = scene;
  60763. _this._basePostProcess = originalPostProcess;
  60764. _this._ratio = ratio;
  60765. // Misc
  60766. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60767. // Finish
  60768. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60769. _this._buildPipeline();
  60770. return _this;
  60771. }
  60772. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  60773. get: function () {
  60774. return this._bloomEnabled;
  60775. },
  60776. set: function (enabled) {
  60777. if (this._bloomEnabled === enabled) {
  60778. return;
  60779. }
  60780. this._bloomEnabled = enabled;
  60781. this._buildPipeline();
  60782. },
  60783. enumerable: true,
  60784. configurable: true
  60785. });
  60786. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  60787. get: function () {
  60788. return this._depthOfFieldEnabled;
  60789. },
  60790. set: function (enabled) {
  60791. if (this._depthOfFieldEnabled === enabled) {
  60792. return;
  60793. }
  60794. this._depthOfFieldEnabled = enabled;
  60795. this._buildPipeline();
  60796. },
  60797. enumerable: true,
  60798. configurable: true
  60799. });
  60800. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  60801. get: function () {
  60802. return this._lensFlareEnabled;
  60803. },
  60804. set: function (enabled) {
  60805. if (this._lensFlareEnabled === enabled) {
  60806. return;
  60807. }
  60808. this._lensFlareEnabled = enabled;
  60809. this._buildPipeline();
  60810. },
  60811. enumerable: true,
  60812. configurable: true
  60813. });
  60814. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  60815. get: function () {
  60816. return this._hdrEnabled;
  60817. },
  60818. set: function (enabled) {
  60819. if (this._hdrEnabled === enabled) {
  60820. return;
  60821. }
  60822. this._hdrEnabled = enabled;
  60823. this._buildPipeline();
  60824. },
  60825. enumerable: true,
  60826. configurable: true
  60827. });
  60828. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  60829. get: function () {
  60830. return this._vlsEnabled;
  60831. },
  60832. set: function (enabled) {
  60833. if (this._vlsEnabled === enabled) {
  60834. return;
  60835. }
  60836. if (enabled) {
  60837. var geometry = this._scene.enableGeometryBufferRenderer();
  60838. if (!geometry) {
  60839. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  60840. return;
  60841. }
  60842. }
  60843. this._vlsEnabled = enabled;
  60844. this._buildPipeline();
  60845. },
  60846. enumerable: true,
  60847. configurable: true
  60848. });
  60849. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  60850. get: function () {
  60851. return this._motionBlurEnabled;
  60852. },
  60853. set: function (enabled) {
  60854. if (this._motionBlurEnabled === enabled) {
  60855. return;
  60856. }
  60857. this._motionBlurEnabled = enabled;
  60858. this._buildPipeline();
  60859. },
  60860. enumerable: true,
  60861. configurable: true
  60862. });
  60863. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  60864. get: function () {
  60865. return this._volumetricLightStepsCount;
  60866. },
  60867. set: function (count) {
  60868. if (this.volumetricLightPostProcess) {
  60869. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  60870. }
  60871. this._volumetricLightStepsCount = count;
  60872. },
  60873. enumerable: true,
  60874. configurable: true
  60875. });
  60876. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  60877. get: function () {
  60878. return this._motionBlurSamples;
  60879. },
  60880. set: function (samples) {
  60881. if (this.motionBlurPostProcess) {
  60882. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  60883. }
  60884. this._motionBlurSamples = samples;
  60885. },
  60886. enumerable: true,
  60887. configurable: true
  60888. });
  60889. StandardRenderingPipeline.prototype._buildPipeline = function () {
  60890. var _this = this;
  60891. var ratio = this._ratio;
  60892. var scene = this._scene;
  60893. this._disposePostProcesses();
  60894. this._reset();
  60895. // Create pass post-process
  60896. if (!this._basePostProcess) {
  60897. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  60898. this.originalPostProcess.onApply = function (effect) {
  60899. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  60900. };
  60901. }
  60902. else {
  60903. this.originalPostProcess = this._basePostProcess;
  60904. }
  60905. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  60906. this._currentDepthOfFieldSource = this.originalPostProcess;
  60907. if (this._vlsEnabled) {
  60908. // Create volumetric light
  60909. this._createVolumetricLightPostProcess(scene, ratio);
  60910. // Create volumetric light final post-process
  60911. 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);
  60912. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  60913. }
  60914. if (this._bloomEnabled) {
  60915. // Create down sample X4 post-process
  60916. this._createDownSampleX4PostProcess(scene, ratio / 2);
  60917. // Create bright pass post-process
  60918. this._createBrightPassPostProcess(scene, ratio / 2);
  60919. // Create gaussian blur post-processes (down sampling blurs)
  60920. this._createBlurPostProcesses(scene, ratio / 4, 1);
  60921. // Create texture adder post-process
  60922. this._createTextureAdderPostProcess(scene, ratio);
  60923. // Create depth-of-field source post-process
  60924. 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);
  60925. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  60926. }
  60927. if (this._lensFlareEnabled) {
  60928. // Create lens flare post-process
  60929. this._createLensFlarePostProcess(scene, ratio);
  60930. // Create depth-of-field source post-process post lens-flare and disable it now
  60931. 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);
  60932. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  60933. }
  60934. if (this._hdrEnabled) {
  60935. // Create luminance
  60936. this._createLuminancePostProcesses(scene, this._floatTextureType);
  60937. // Create HDR
  60938. this._createHdrPostProcess(scene, ratio);
  60939. // Create depth-of-field source post-process post hdr and disable it now
  60940. 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);
  60941. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  60942. }
  60943. if (this._depthOfFieldEnabled) {
  60944. // Create gaussian blur used by depth-of-field
  60945. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  60946. // Create depth-of-field post-process
  60947. this._createDepthOfFieldPostProcess(scene, ratio);
  60948. }
  60949. if (this._motionBlurEnabled) {
  60950. // Create motion blur post-process
  60951. this._createMotionBlurPostProcess(scene, ratio);
  60952. }
  60953. if (this._cameras !== null) {
  60954. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  60955. }
  60956. };
  60957. // Down Sample X4 Post-Processs
  60958. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  60959. var _this = this;
  60960. var downSampleX4Offsets = new Array(32);
  60961. 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);
  60962. this.downSampleX4PostProcess.onApply = function (effect) {
  60963. var id = 0;
  60964. var width = _this.downSampleX4PostProcess.width;
  60965. var height = _this.downSampleX4PostProcess.height;
  60966. for (var i = -2; i < 2; i++) {
  60967. for (var j = -2; j < 2; j++) {
  60968. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  60969. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  60970. id += 2;
  60971. }
  60972. }
  60973. effect.setArray2("dsOffsets", downSampleX4Offsets);
  60974. };
  60975. // Add to pipeline
  60976. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  60977. };
  60978. // Brightpass Post-Process
  60979. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  60980. var _this = this;
  60981. var brightOffsets = new Array(8);
  60982. 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);
  60983. this.brightPassPostProcess.onApply = function (effect) {
  60984. var sU = (1.0 / _this.brightPassPostProcess.width);
  60985. var sV = (1.0 / _this.brightPassPostProcess.height);
  60986. brightOffsets[0] = -0.5 * sU;
  60987. brightOffsets[1] = 0.5 * sV;
  60988. brightOffsets[2] = 0.5 * sU;
  60989. brightOffsets[3] = 0.5 * sV;
  60990. brightOffsets[4] = -0.5 * sU;
  60991. brightOffsets[5] = -0.5 * sV;
  60992. brightOffsets[6] = 0.5 * sU;
  60993. brightOffsets[7] = -0.5 * sV;
  60994. effect.setArray2("dsOffsets", brightOffsets);
  60995. effect.setFloat("brightThreshold", _this.brightThreshold);
  60996. };
  60997. // Add to pipeline
  60998. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  60999. };
  61000. // Create blur H&V post-processes
  61001. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  61002. var _this = this;
  61003. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  61004. var engine = scene.getEngine();
  61005. 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);
  61006. 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);
  61007. blurX.onActivateObservable.add(function () {
  61008. var dw = blurX.width / engine.getRenderWidth();
  61009. blurX.kernel = _this[blurWidthKey] * dw;
  61010. });
  61011. blurY.onActivateObservable.add(function () {
  61012. var dw = blurY.height / engine.getRenderHeight();
  61013. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  61014. });
  61015. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  61016. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  61017. this.blurHPostProcesses.push(blurX);
  61018. this.blurVPostProcesses.push(blurY);
  61019. };
  61020. // Create texture adder post-process
  61021. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  61022. var _this = this;
  61023. 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);
  61024. this.textureAdderPostProcess.onApply = function (effect) {
  61025. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  61026. effect.setTexture("lensSampler", _this.lensTexture);
  61027. effect.setFloat("exposure", _this.exposure);
  61028. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  61029. };
  61030. // Add to pipeline
  61031. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  61032. };
  61033. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  61034. var _this = this;
  61035. var geometryRenderer = scene.enableGeometryBufferRenderer();
  61036. geometryRenderer.enablePosition = true;
  61037. var geometry = geometryRenderer.getGBuffer();
  61038. // Base post-process
  61039. 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));
  61040. var depthValues = BABYLON.Vector2.Zero();
  61041. this.volumetricLightPostProcess.onApply = function (effect) {
  61042. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  61043. var generator = _this.sourceLight.getShadowGenerator();
  61044. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  61045. effect.setTexture("positionSampler", geometry.textures[2]);
  61046. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  61047. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  61048. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  61049. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  61050. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  61051. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  61052. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  61053. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  61054. effect.setVector2("depthValues", depthValues);
  61055. }
  61056. };
  61057. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  61058. // Smooth
  61059. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  61060. // Merge
  61061. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  61062. this.volumetricLightMergePostProces.onApply = function (effect) {
  61063. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  61064. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  61065. };
  61066. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  61067. };
  61068. // Create luminance
  61069. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  61070. var _this = this;
  61071. // Create luminance
  61072. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  61073. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  61074. var offsets = [];
  61075. this.luminancePostProcess.onApply = function (effect) {
  61076. var sU = (1.0 / _this.luminancePostProcess.width);
  61077. var sV = (1.0 / _this.luminancePostProcess.height);
  61078. offsets[0] = -0.5 * sU;
  61079. offsets[1] = 0.5 * sV;
  61080. offsets[2] = 0.5 * sU;
  61081. offsets[3] = 0.5 * sV;
  61082. offsets[4] = -0.5 * sU;
  61083. offsets[5] = -0.5 * sV;
  61084. offsets[6] = 0.5 * sU;
  61085. offsets[7] = -0.5 * sV;
  61086. effect.setArray2("lumOffsets", offsets);
  61087. };
  61088. // Add to pipeline
  61089. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  61090. // Create down sample luminance
  61091. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  61092. var size = Math.pow(3, i);
  61093. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  61094. if (i === 0) {
  61095. defines += "#define FINAL_DOWN_SAMPLER";
  61096. }
  61097. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  61098. this.luminanceDownSamplePostProcesses.push(postProcess);
  61099. }
  61100. // Create callbacks and add effects
  61101. var lastLuminance = this.luminancePostProcess;
  61102. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  61103. var downSampleOffsets = new Array(18);
  61104. pp.onApply = function (effect) {
  61105. if (!lastLuminance) {
  61106. return;
  61107. }
  61108. var id = 0;
  61109. for (var x = -1; x < 2; x++) {
  61110. for (var y = -1; y < 2; y++) {
  61111. downSampleOffsets[id] = x / lastLuminance.width;
  61112. downSampleOffsets[id + 1] = y / lastLuminance.height;
  61113. id += 2;
  61114. }
  61115. }
  61116. effect.setArray2("dsOffsets", downSampleOffsets);
  61117. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  61118. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  61119. lastLuminance = _this.luminancePostProcess;
  61120. }
  61121. else {
  61122. lastLuminance = pp;
  61123. }
  61124. };
  61125. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  61126. pp.onAfterRender = function (effect) {
  61127. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  61128. 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);
  61129. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  61130. };
  61131. }
  61132. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  61133. });
  61134. };
  61135. // Create HDR post-process
  61136. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  61137. var _this = this;
  61138. 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);
  61139. var outputLiminance = 1;
  61140. var time = 0;
  61141. var lastTime = 0;
  61142. this.hdrPostProcess.onApply = function (effect) {
  61143. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  61144. time += scene.getEngine().getDeltaTime();
  61145. if (outputLiminance < 0) {
  61146. outputLiminance = _this._hdrCurrentLuminance;
  61147. }
  61148. else {
  61149. var dt = (lastTime - time) / 1000.0;
  61150. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  61151. outputLiminance += _this.hdrDecreaseRate * dt;
  61152. }
  61153. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  61154. outputLiminance -= _this.hdrIncreaseRate * dt;
  61155. }
  61156. else {
  61157. outputLiminance = _this._hdrCurrentLuminance;
  61158. }
  61159. }
  61160. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  61161. effect.setFloat("averageLuminance", outputLiminance);
  61162. lastTime = time;
  61163. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  61164. };
  61165. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  61166. };
  61167. // Create lens flare post-process
  61168. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  61169. var _this = this;
  61170. 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);
  61171. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  61172. this._createBlurPostProcesses(scene, ratio / 4, 2);
  61173. 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);
  61174. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  61175. var resolution = new BABYLON.Vector2(0, 0);
  61176. // Lens flare
  61177. this.lensFlarePostProcess.onApply = function (effect) {
  61178. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  61179. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  61180. effect.setFloat("strength", _this.lensFlareStrength);
  61181. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  61182. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  61183. // Shift
  61184. resolution.x = _this.lensFlarePostProcess.width;
  61185. resolution.y = _this.lensFlarePostProcess.height;
  61186. effect.setVector2("resolution", resolution);
  61187. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  61188. };
  61189. // Compose
  61190. 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);
  61191. 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);
  61192. this.lensFlareComposePostProcess.onApply = function (effect) {
  61193. if (!_this._scene.activeCamera) {
  61194. return;
  61195. }
  61196. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  61197. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  61198. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  61199. // Lens start rotation matrix
  61200. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  61201. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  61202. 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));
  61203. camRot *= 4.0;
  61204. 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);
  61205. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  61206. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  61207. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  61208. };
  61209. };
  61210. // Create depth-of-field post-process
  61211. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  61212. var _this = this;
  61213. 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);
  61214. this.depthOfFieldPostProcess.onApply = function (effect) {
  61215. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  61216. effect.setTexture("depthSampler", _this._getDepthTexture());
  61217. effect.setFloat("distance", _this.depthOfFieldDistance);
  61218. };
  61219. // Add to pipeline
  61220. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  61221. };
  61222. // Create motion blur post-process
  61223. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  61224. var _this = this;
  61225. 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);
  61226. var motionScale = 0;
  61227. var prevViewProjection = BABYLON.Matrix.Identity();
  61228. var invViewProjection = BABYLON.Matrix.Identity();
  61229. var viewProjection = BABYLON.Matrix.Identity();
  61230. var screenSize = BABYLON.Vector2.Zero();
  61231. this.motionBlurPostProcess.onApply = function (effect) {
  61232. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  61233. viewProjection.invertToRef(invViewProjection);
  61234. effect.setMatrix("inverseViewProjection", invViewProjection);
  61235. effect.setMatrix("prevViewProjection", prevViewProjection);
  61236. prevViewProjection = viewProjection;
  61237. screenSize.x = _this.motionBlurPostProcess.width;
  61238. screenSize.y = _this.motionBlurPostProcess.height;
  61239. effect.setVector2("screenSize", screenSize);
  61240. motionScale = scene.getEngine().getFps() / 60.0;
  61241. effect.setFloat("motionScale", motionScale);
  61242. effect.setFloat("motionStrength", _this.motionStrength);
  61243. effect.setTexture("depthSampler", _this._getDepthTexture());
  61244. };
  61245. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  61246. };
  61247. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  61248. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  61249. var renderer = this._scene.enableGeometryBufferRenderer();
  61250. return renderer.getGBuffer().textures[0];
  61251. }
  61252. return this._scene.enableDepthRenderer().getDepthMap();
  61253. };
  61254. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  61255. for (var i = 0; i < this._cameras.length; i++) {
  61256. var camera = this._cameras[i];
  61257. if (this.originalPostProcess) {
  61258. this.originalPostProcess.dispose(camera);
  61259. }
  61260. if (this.downSampleX4PostProcess) {
  61261. this.downSampleX4PostProcess.dispose(camera);
  61262. }
  61263. if (this.brightPassPostProcess) {
  61264. this.brightPassPostProcess.dispose(camera);
  61265. }
  61266. if (this.textureAdderPostProcess) {
  61267. this.textureAdderPostProcess.dispose(camera);
  61268. }
  61269. if (this.textureAdderFinalPostProcess) {
  61270. this.textureAdderFinalPostProcess.dispose(camera);
  61271. }
  61272. if (this.volumetricLightPostProcess) {
  61273. this.volumetricLightPostProcess.dispose(camera);
  61274. }
  61275. if (this.volumetricLightSmoothXPostProcess) {
  61276. this.volumetricLightSmoothXPostProcess.dispose(camera);
  61277. }
  61278. if (this.volumetricLightSmoothYPostProcess) {
  61279. this.volumetricLightSmoothYPostProcess.dispose(camera);
  61280. }
  61281. if (this.volumetricLightMergePostProces) {
  61282. this.volumetricLightMergePostProces.dispose(camera);
  61283. }
  61284. if (this.volumetricLightFinalPostProcess) {
  61285. this.volumetricLightFinalPostProcess.dispose(camera);
  61286. }
  61287. if (this.lensFlarePostProcess) {
  61288. this.lensFlarePostProcess.dispose(camera);
  61289. }
  61290. if (this.lensFlareComposePostProcess) {
  61291. this.lensFlareComposePostProcess.dispose(camera);
  61292. }
  61293. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  61294. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  61295. }
  61296. if (this.luminancePostProcess) {
  61297. this.luminancePostProcess.dispose(camera);
  61298. }
  61299. if (this.hdrPostProcess) {
  61300. this.hdrPostProcess.dispose(camera);
  61301. }
  61302. if (this.hdrFinalPostProcess) {
  61303. this.hdrFinalPostProcess.dispose(camera);
  61304. }
  61305. if (this.depthOfFieldPostProcess) {
  61306. this.depthOfFieldPostProcess.dispose(camera);
  61307. }
  61308. if (this.motionBlurPostProcess) {
  61309. this.motionBlurPostProcess.dispose(camera);
  61310. }
  61311. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  61312. this.blurHPostProcesses[j].dispose(camera);
  61313. }
  61314. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  61315. this.blurVPostProcesses[j].dispose(camera);
  61316. }
  61317. }
  61318. this.originalPostProcess = null;
  61319. this.downSampleX4PostProcess = null;
  61320. this.brightPassPostProcess = null;
  61321. this.textureAdderPostProcess = null;
  61322. this.textureAdderFinalPostProcess = null;
  61323. this.volumetricLightPostProcess = null;
  61324. this.volumetricLightSmoothXPostProcess = null;
  61325. this.volumetricLightSmoothYPostProcess = null;
  61326. this.volumetricLightMergePostProces = null;
  61327. this.volumetricLightFinalPostProcess = null;
  61328. this.lensFlarePostProcess = null;
  61329. this.lensFlareComposePostProcess = null;
  61330. this.luminancePostProcess = null;
  61331. this.hdrPostProcess = null;
  61332. this.hdrFinalPostProcess = null;
  61333. this.depthOfFieldPostProcess = null;
  61334. this.motionBlurPostProcess = null;
  61335. this.luminanceDownSamplePostProcesses = [];
  61336. this.blurHPostProcesses = [];
  61337. this.blurVPostProcesses = [];
  61338. };
  61339. // Dispose
  61340. StandardRenderingPipeline.prototype.dispose = function () {
  61341. this._disposePostProcesses();
  61342. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61343. _super.prototype.dispose.call(this);
  61344. };
  61345. // Serialize rendering pipeline
  61346. StandardRenderingPipeline.prototype.serialize = function () {
  61347. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61348. serializationObject.customType = "StandardRenderingPipeline";
  61349. return serializationObject;
  61350. };
  61351. /**
  61352. * Static members
  61353. */
  61354. // Parse serialized pipeline
  61355. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61356. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  61357. };
  61358. // Luminance steps
  61359. StandardRenderingPipeline.LuminanceSteps = 6;
  61360. __decorate([
  61361. BABYLON.serialize()
  61362. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  61363. __decorate([
  61364. BABYLON.serialize()
  61365. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  61366. __decorate([
  61367. BABYLON.serialize()
  61368. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  61369. __decorate([
  61370. BABYLON.serialize()
  61371. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  61372. __decorate([
  61373. BABYLON.serializeAsTexture("lensTexture")
  61374. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  61375. __decorate([
  61376. BABYLON.serialize()
  61377. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  61378. __decorate([
  61379. BABYLON.serialize()
  61380. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  61381. __decorate([
  61382. BABYLON.serialize()
  61383. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  61384. __decorate([
  61385. BABYLON.serialize()
  61386. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  61387. __decorate([
  61388. BABYLON.serialize()
  61389. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  61390. __decorate([
  61391. BABYLON.serialize()
  61392. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  61393. __decorate([
  61394. BABYLON.serializeAsTexture("lensColorTexture")
  61395. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  61396. __decorate([
  61397. BABYLON.serialize()
  61398. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  61399. __decorate([
  61400. BABYLON.serialize()
  61401. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  61402. __decorate([
  61403. BABYLON.serialize()
  61404. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  61405. __decorate([
  61406. BABYLON.serialize()
  61407. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  61408. __decorate([
  61409. BABYLON.serializeAsTexture("lensStarTexture")
  61410. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  61411. __decorate([
  61412. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  61413. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  61414. __decorate([
  61415. BABYLON.serialize()
  61416. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  61417. __decorate([
  61418. BABYLON.serialize()
  61419. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  61420. __decorate([
  61421. BABYLON.serialize()
  61422. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  61423. __decorate([
  61424. BABYLON.serialize()
  61425. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  61426. __decorate([
  61427. BABYLON.serialize()
  61428. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  61429. __decorate([
  61430. BABYLON.serialize()
  61431. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  61432. __decorate([
  61433. BABYLON.serialize()
  61434. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  61435. __decorate([
  61436. BABYLON.serialize()
  61437. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  61438. __decorate([
  61439. BABYLON.serialize()
  61440. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  61441. __decorate([
  61442. BABYLON.serialize()
  61443. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  61444. __decorate([
  61445. BABYLON.serialize()
  61446. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  61447. __decorate([
  61448. BABYLON.serialize()
  61449. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  61450. return StandardRenderingPipeline;
  61451. }(BABYLON.PostProcessRenderPipeline));
  61452. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  61453. })(BABYLON || (BABYLON = {}));
  61454. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  61455. var BABYLON;
  61456. (function (BABYLON) {
  61457. var FxaaPostProcess = /** @class */ (function (_super) {
  61458. __extends(FxaaPostProcess, _super);
  61459. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  61460. if (camera === void 0) { camera = null; }
  61461. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61462. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  61463. _this.onApplyObservable.add(function (effect) {
  61464. var texelSize = _this.texelSize;
  61465. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  61466. });
  61467. return _this;
  61468. }
  61469. return FxaaPostProcess;
  61470. }(BABYLON.PostProcess));
  61471. BABYLON.FxaaPostProcess = FxaaPostProcess;
  61472. })(BABYLON || (BABYLON = {}));
  61473. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  61474. var BABYLON;
  61475. (function (BABYLON) {
  61476. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  61477. __extends(DefaultRenderingPipeline, _super);
  61478. /**
  61479. * @constructor
  61480. * @param {string} name - The rendering pipeline name
  61481. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61482. * @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)
  61483. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61484. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  61485. */
  61486. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  61487. if (automaticBuild === void 0) { automaticBuild = true; }
  61488. var _this = _super.call(this, scene.getEngine(), name) || this;
  61489. _this.PassPostProcessId = "PassPostProcessEffect";
  61490. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  61491. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  61492. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  61493. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  61494. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  61495. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  61496. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  61497. // IAnimatable
  61498. _this.animations = [];
  61499. // Values
  61500. _this._bloomEnabled = false;
  61501. _this._fxaaEnabled = false;
  61502. _this._imageProcessingEnabled = true;
  61503. _this._bloomScale = 0.6;
  61504. _this._buildAllowed = true;
  61505. /**
  61506. * Specifies the size of the bloom blur kernel, relative to the final output size
  61507. */
  61508. _this.bloomKernel = 64;
  61509. /**
  61510. * Specifies the weight of the bloom in the final rendering
  61511. */
  61512. _this._bloomWeight = 0.15;
  61513. _this._cameras = cameras || [];
  61514. _this._buildAllowed = automaticBuild;
  61515. // Initialize
  61516. _this._scene = scene;
  61517. var caps = _this._scene.getEngine().getCaps();
  61518. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  61519. // Misc
  61520. if (_this._hdr) {
  61521. if (caps.textureHalfFloatRender) {
  61522. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61523. }
  61524. else if (caps.textureFloatRender) {
  61525. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61526. }
  61527. }
  61528. else {
  61529. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61530. }
  61531. // Attach
  61532. scene.postProcessRenderPipelineManager.addPipeline(_this);
  61533. _this._buildPipeline();
  61534. return _this;
  61535. }
  61536. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  61537. get: function () {
  61538. return this._bloomWeight;
  61539. },
  61540. set: function (value) {
  61541. if (this._bloomWeight === value) {
  61542. return;
  61543. }
  61544. this._bloomWeight = value;
  61545. if (this._hdr && this.copyBack) {
  61546. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  61547. }
  61548. },
  61549. enumerable: true,
  61550. configurable: true
  61551. });
  61552. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  61553. get: function () {
  61554. return this._bloomScale;
  61555. },
  61556. set: function (value) {
  61557. if (this._bloomScale === value) {
  61558. return;
  61559. }
  61560. this._bloomScale = value;
  61561. this._buildPipeline();
  61562. },
  61563. enumerable: true,
  61564. configurable: true
  61565. });
  61566. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  61567. get: function () {
  61568. return this._bloomEnabled;
  61569. },
  61570. set: function (enabled) {
  61571. if (this._bloomEnabled === enabled) {
  61572. return;
  61573. }
  61574. this._bloomEnabled = enabled;
  61575. this._buildPipeline();
  61576. },
  61577. enumerable: true,
  61578. configurable: true
  61579. });
  61580. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  61581. get: function () {
  61582. return this._fxaaEnabled;
  61583. },
  61584. set: function (enabled) {
  61585. if (this._fxaaEnabled === enabled) {
  61586. return;
  61587. }
  61588. this._fxaaEnabled = enabled;
  61589. this._buildPipeline();
  61590. },
  61591. enumerable: true,
  61592. configurable: true
  61593. });
  61594. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  61595. get: function () {
  61596. return this._imageProcessingEnabled;
  61597. },
  61598. set: function (enabled) {
  61599. if (this._imageProcessingEnabled === enabled) {
  61600. return;
  61601. }
  61602. this._imageProcessingEnabled = enabled;
  61603. this._buildPipeline();
  61604. },
  61605. enumerable: true,
  61606. configurable: true
  61607. });
  61608. /**
  61609. * Force the compilation of the entire pipeline.
  61610. */
  61611. DefaultRenderingPipeline.prototype.prepare = function () {
  61612. var previousState = this._buildAllowed;
  61613. this._buildAllowed = true;
  61614. this._buildPipeline();
  61615. this._buildAllowed = previousState;
  61616. };
  61617. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  61618. var _this = this;
  61619. if (!this._buildAllowed) {
  61620. return;
  61621. }
  61622. var engine = this._scene.getEngine();
  61623. this._disposePostProcesses();
  61624. this._reset();
  61625. if (this.bloomEnabled) {
  61626. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61627. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  61628. if (!this._hdr) {
  61629. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61630. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  61631. this.highlights.autoClear = false;
  61632. this.highlights.alwaysForcePOT = true;
  61633. }
  61634. 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);
  61635. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  61636. this.blurX.alwaysForcePOT = true;
  61637. this.blurX.autoClear = false;
  61638. this.blurX.onActivateObservable.add(function () {
  61639. var dw = _this.blurX.width / engine.getRenderWidth(true);
  61640. _this.blurX.kernel = _this.bloomKernel * dw;
  61641. });
  61642. 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);
  61643. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  61644. this.blurY.alwaysForcePOT = true;
  61645. this.blurY.autoClear = false;
  61646. this.blurY.onActivateObservable.add(function () {
  61647. var dh = _this.blurY.height / engine.getRenderHeight(true);
  61648. _this.blurY.kernel = _this.bloomKernel * dh;
  61649. });
  61650. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61651. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  61652. this.copyBack.alwaysForcePOT = true;
  61653. if (this._hdr) {
  61654. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  61655. var w = this.bloomWeight;
  61656. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  61657. }
  61658. else {
  61659. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  61660. }
  61661. this.copyBack.autoClear = false;
  61662. }
  61663. if (this._imageProcessingEnabled) {
  61664. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61665. if (this._hdr) {
  61666. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  61667. }
  61668. else {
  61669. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  61670. }
  61671. }
  61672. if (this.fxaaEnabled) {
  61673. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61674. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  61675. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61676. }
  61677. else if (this._hdr && this.imageProcessing) {
  61678. this.finalMerge = this.imageProcessing;
  61679. }
  61680. else {
  61681. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61682. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  61683. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61684. }
  61685. if (this.bloomEnabled) {
  61686. if (this._hdr) {
  61687. this.copyBack.shareOutputWith(this.blurX);
  61688. if (this.imageProcessing) {
  61689. this.imageProcessing.shareOutputWith(this.pass);
  61690. this.imageProcessing.autoClear = false;
  61691. }
  61692. else if (this.fxaa) {
  61693. this.fxaa.shareOutputWith(this.pass);
  61694. }
  61695. else {
  61696. this.finalMerge.shareOutputWith(this.pass);
  61697. }
  61698. }
  61699. else {
  61700. if (this.fxaa) {
  61701. this.fxaa.shareOutputWith(this.pass);
  61702. }
  61703. else {
  61704. this.finalMerge.shareOutputWith(this.pass);
  61705. }
  61706. }
  61707. }
  61708. if (this._cameras !== null) {
  61709. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  61710. }
  61711. };
  61712. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  61713. for (var i = 0; i < this._cameras.length; i++) {
  61714. var camera = this._cameras[i];
  61715. if (this.pass) {
  61716. this.pass.dispose(camera);
  61717. }
  61718. if (this.highlights) {
  61719. this.highlights.dispose(camera);
  61720. }
  61721. if (this.blurX) {
  61722. this.blurX.dispose(camera);
  61723. }
  61724. if (this.blurY) {
  61725. this.blurY.dispose(camera);
  61726. }
  61727. if (this.copyBack) {
  61728. this.copyBack.dispose(camera);
  61729. }
  61730. if (this.imageProcessing) {
  61731. this.imageProcessing.dispose(camera);
  61732. }
  61733. if (this.fxaa) {
  61734. this.fxaa.dispose(camera);
  61735. }
  61736. if (this.finalMerge) {
  61737. this.finalMerge.dispose(camera);
  61738. }
  61739. }
  61740. this.pass = null;
  61741. this.highlights = null;
  61742. this.blurX = null;
  61743. this.blurY = null;
  61744. this.copyBack = null;
  61745. this.imageProcessing = null;
  61746. this.fxaa = null;
  61747. this.finalMerge = null;
  61748. };
  61749. // Dispose
  61750. DefaultRenderingPipeline.prototype.dispose = function () {
  61751. this._disposePostProcesses();
  61752. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61753. _super.prototype.dispose.call(this);
  61754. };
  61755. // Serialize rendering pipeline
  61756. DefaultRenderingPipeline.prototype.serialize = function () {
  61757. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61758. serializationObject.customType = "DefaultRenderingPipeline";
  61759. return serializationObject;
  61760. };
  61761. // Parse serialized pipeline
  61762. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61763. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  61764. };
  61765. __decorate([
  61766. BABYLON.serialize()
  61767. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  61768. __decorate([
  61769. BABYLON.serialize()
  61770. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  61771. __decorate([
  61772. BABYLON.serialize()
  61773. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  61774. __decorate([
  61775. BABYLON.serialize()
  61776. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  61777. __decorate([
  61778. BABYLON.serialize()
  61779. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  61780. __decorate([
  61781. BABYLON.serialize()
  61782. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  61783. __decorate([
  61784. BABYLON.serialize()
  61785. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  61786. __decorate([
  61787. BABYLON.serialize()
  61788. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  61789. return DefaultRenderingPipeline;
  61790. }(BABYLON.PostProcessRenderPipeline));
  61791. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  61792. })(BABYLON || (BABYLON = {}));
  61793. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  61794. var BABYLON;
  61795. (function (BABYLON) {
  61796. var GeometryBufferRenderer = /** @class */ (function () {
  61797. function GeometryBufferRenderer(scene, ratio) {
  61798. if (ratio === void 0) { ratio = 1; }
  61799. this._enablePosition = false;
  61800. this._scene = scene;
  61801. this._ratio = ratio;
  61802. // Render target
  61803. this._createRenderTargets();
  61804. }
  61805. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  61806. set: function (meshes) {
  61807. this._multiRenderTarget.renderList = meshes;
  61808. },
  61809. enumerable: true,
  61810. configurable: true
  61811. });
  61812. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  61813. get: function () {
  61814. return this._multiRenderTarget.isSupported;
  61815. },
  61816. enumerable: true,
  61817. configurable: true
  61818. });
  61819. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  61820. get: function () {
  61821. return this._enablePosition;
  61822. },
  61823. set: function (enable) {
  61824. this._enablePosition = enable;
  61825. this.dispose();
  61826. this._createRenderTargets();
  61827. },
  61828. enumerable: true,
  61829. configurable: true
  61830. });
  61831. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  61832. var material = subMesh.getMaterial();
  61833. if (material && material.disableDepthWrite) {
  61834. return false;
  61835. }
  61836. var defines = [];
  61837. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  61838. var mesh = subMesh.getMesh();
  61839. // Alpha test
  61840. if (material && material.needAlphaTesting()) {
  61841. defines.push("#define ALPHATEST");
  61842. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61843. attribs.push(BABYLON.VertexBuffer.UVKind);
  61844. defines.push("#define UV1");
  61845. }
  61846. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61847. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61848. defines.push("#define UV2");
  61849. }
  61850. }
  61851. // Buffers
  61852. if (this._enablePosition) {
  61853. defines.push("#define POSITION");
  61854. }
  61855. // Bones
  61856. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61857. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61858. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61859. if (mesh.numBoneInfluencers > 4) {
  61860. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61861. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61862. }
  61863. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61864. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  61865. }
  61866. else {
  61867. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61868. }
  61869. // Instances
  61870. if (useInstances) {
  61871. defines.push("#define INSTANCES");
  61872. attribs.push("world0");
  61873. attribs.push("world1");
  61874. attribs.push("world2");
  61875. attribs.push("world3");
  61876. }
  61877. // Get correct effect
  61878. var join = defines.join("\n");
  61879. if (this._cachedDefines !== join) {
  61880. this._cachedDefines = join;
  61881. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  61882. }
  61883. return this._effect.isReady();
  61884. };
  61885. GeometryBufferRenderer.prototype.getGBuffer = function () {
  61886. return this._multiRenderTarget;
  61887. };
  61888. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  61889. get: function () {
  61890. return this._multiRenderTarget.samples;
  61891. },
  61892. set: function (value) {
  61893. this._multiRenderTarget.samples = value;
  61894. },
  61895. enumerable: true,
  61896. configurable: true
  61897. });
  61898. // Methods
  61899. GeometryBufferRenderer.prototype.dispose = function () {
  61900. this.getGBuffer().dispose();
  61901. };
  61902. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  61903. var _this = this;
  61904. var engine = this._scene.getEngine();
  61905. var count = this._enablePosition ? 3 : 2;
  61906. 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 });
  61907. if (!this.isSupported) {
  61908. return;
  61909. }
  61910. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61911. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61912. this._multiRenderTarget.refreshRate = 1;
  61913. this._multiRenderTarget.renderParticles = false;
  61914. this._multiRenderTarget.renderList = null;
  61915. // set default depth value to 1.0 (far away)
  61916. this._multiRenderTarget.onClearObservable.add(function (engine) {
  61917. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  61918. });
  61919. // Custom render function
  61920. var renderSubMesh = function (subMesh) {
  61921. var mesh = subMesh.getRenderingMesh();
  61922. var scene = _this._scene;
  61923. var engine = scene.getEngine();
  61924. var material = subMesh.getMaterial();
  61925. if (!material) {
  61926. return;
  61927. }
  61928. // Culling
  61929. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  61930. // Managing instances
  61931. var batch = mesh._getInstancesRenderList(subMesh._id);
  61932. if (batch.mustReturn) {
  61933. return;
  61934. }
  61935. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61936. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  61937. engine.enableEffect(_this._effect);
  61938. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  61939. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  61940. _this._effect.setMatrix("view", scene.getViewMatrix());
  61941. // Alpha test
  61942. if (material && material.needAlphaTesting()) {
  61943. var alphaTexture = material.getAlphaTestTexture();
  61944. if (alphaTexture) {
  61945. _this._effect.setTexture("diffuseSampler", alphaTexture);
  61946. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61947. }
  61948. }
  61949. // Bones
  61950. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61951. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61952. }
  61953. // Draw
  61954. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61955. }
  61956. };
  61957. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61958. var index;
  61959. if (depthOnlySubMeshes.length) {
  61960. engine.setColorWrite(false);
  61961. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61962. renderSubMesh(depthOnlySubMeshes.data[index]);
  61963. }
  61964. engine.setColorWrite(true);
  61965. }
  61966. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61967. renderSubMesh(opaqueSubMeshes.data[index]);
  61968. }
  61969. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61970. renderSubMesh(alphaTestSubMeshes.data[index]);
  61971. }
  61972. };
  61973. };
  61974. return GeometryBufferRenderer;
  61975. }());
  61976. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  61977. })(BABYLON || (BABYLON = {}));
  61978. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  61979. var BABYLON;
  61980. (function (BABYLON) {
  61981. var RefractionPostProcess = /** @class */ (function (_super) {
  61982. __extends(RefractionPostProcess, _super);
  61983. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  61984. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  61985. _this.color = color;
  61986. _this.depth = depth;
  61987. _this.colorLevel = colorLevel;
  61988. _this.onActivateObservable.add(function (cam) {
  61989. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  61990. });
  61991. _this.onApplyObservable.add(function (effect) {
  61992. effect.setColor3("baseColor", _this.color);
  61993. effect.setFloat("depth", _this.depth);
  61994. effect.setFloat("colorLevel", _this.colorLevel);
  61995. effect.setTexture("refractionSampler", _this._refRexture);
  61996. });
  61997. return _this;
  61998. }
  61999. // Methods
  62000. RefractionPostProcess.prototype.dispose = function (camera) {
  62001. if (this._refRexture) {
  62002. this._refRexture.dispose();
  62003. }
  62004. _super.prototype.dispose.call(this, camera);
  62005. };
  62006. return RefractionPostProcess;
  62007. }(BABYLON.PostProcess));
  62008. BABYLON.RefractionPostProcess = RefractionPostProcess;
  62009. })(BABYLON || (BABYLON = {}));
  62010. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  62011. var BABYLON;
  62012. (function (BABYLON) {
  62013. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  62014. __extends(BlackAndWhitePostProcess, _super);
  62015. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  62016. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  62017. _this.degree = 1;
  62018. _this.onApplyObservable.add(function (effect) {
  62019. effect.setFloat("degree", _this.degree);
  62020. });
  62021. return _this;
  62022. }
  62023. return BlackAndWhitePostProcess;
  62024. }(BABYLON.PostProcess));
  62025. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  62026. })(BABYLON || (BABYLON = {}));
  62027. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  62028. var BABYLON;
  62029. (function (BABYLON) {
  62030. var ConvolutionPostProcess = /** @class */ (function (_super) {
  62031. __extends(ConvolutionPostProcess, _super);
  62032. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  62033. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  62034. _this.kernel = kernel;
  62035. _this.onApply = function (effect) {
  62036. effect.setFloat2("screenSize", _this.width, _this.height);
  62037. effect.setArray("kernel", _this.kernel);
  62038. };
  62039. return _this;
  62040. }
  62041. // Statics
  62042. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  62043. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  62044. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  62045. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  62046. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  62047. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  62048. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  62049. return ConvolutionPostProcess;
  62050. }(BABYLON.PostProcess));
  62051. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  62052. })(BABYLON || (BABYLON = {}));
  62053. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  62054. var BABYLON;
  62055. (function (BABYLON) {
  62056. var FilterPostProcess = /** @class */ (function (_super) {
  62057. __extends(FilterPostProcess, _super);
  62058. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  62059. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  62060. _this.kernelMatrix = kernelMatrix;
  62061. _this.onApply = function (effect) {
  62062. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  62063. };
  62064. return _this;
  62065. }
  62066. return FilterPostProcess;
  62067. }(BABYLON.PostProcess));
  62068. BABYLON.FilterPostProcess = FilterPostProcess;
  62069. })(BABYLON || (BABYLON = {}));
  62070. //# sourceMappingURL=babylon.filterPostProcess.js.map
  62071. var BABYLON;
  62072. (function (BABYLON) {
  62073. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  62074. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  62075. __extends(VolumetricLightScatteringPostProcess, _super);
  62076. /**
  62077. * @constructor
  62078. * @param {string} name - The post-process name
  62079. * @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)
  62080. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  62081. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  62082. * @param {number} samples - The post-process quality, default 100
  62083. * @param {number} samplingMode - The post-process filtering mode
  62084. * @param {BABYLON.Engine} engine - The babylon engine
  62085. * @param {boolean} reusable - If the post-process is reusable
  62086. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  62087. */
  62088. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  62089. if (samples === void 0) { samples = 100; }
  62090. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62091. 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;
  62092. _this._screenCoordinates = BABYLON.Vector2.Zero();
  62093. /**
  62094. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  62095. * @type {Vector3}
  62096. */
  62097. _this.customMeshPosition = BABYLON.Vector3.Zero();
  62098. /**
  62099. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  62100. * @type {boolean}
  62101. */
  62102. _this.useCustomMeshPosition = false;
  62103. /**
  62104. * If the post-process should inverse the light scattering direction
  62105. * @type {boolean}
  62106. */
  62107. _this.invert = true;
  62108. /**
  62109. * Array containing the excluded meshes not rendered in the internal pass
  62110. */
  62111. _this.excludedMeshes = new Array();
  62112. /**
  62113. * Controls the overall intensity of the post-process
  62114. * @type {number}
  62115. */
  62116. _this.exposure = 0.3;
  62117. /**
  62118. * Dissipates each sample's contribution in range [0, 1]
  62119. * @type {number}
  62120. */
  62121. _this.decay = 0.96815;
  62122. /**
  62123. * Controls the overall intensity of each sample
  62124. * @type {number}
  62125. */
  62126. _this.weight = 0.58767;
  62127. /**
  62128. * Controls the density of each sample
  62129. * @type {number}
  62130. */
  62131. _this.density = 0.926;
  62132. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  62133. engine = scene.getEngine();
  62134. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  62135. // Configure mesh
  62136. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  62137. // Configure
  62138. _this._createPass(scene, ratio.passRatio || ratio);
  62139. _this.onActivate = function (camera) {
  62140. if (!_this.isSupported) {
  62141. _this.dispose(camera);
  62142. }
  62143. _this.onActivate = null;
  62144. };
  62145. _this.onApplyObservable.add(function (effect) {
  62146. _this._updateMeshScreenCoordinates(scene);
  62147. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  62148. effect.setFloat("exposure", _this.exposure);
  62149. effect.setFloat("decay", _this.decay);
  62150. effect.setFloat("weight", _this.weight);
  62151. effect.setFloat("density", _this.density);
  62152. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  62153. });
  62154. return _this;
  62155. }
  62156. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  62157. get: function () {
  62158. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  62159. return false;
  62160. },
  62161. set: function (useDiffuseColor) {
  62162. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  62163. },
  62164. enumerable: true,
  62165. configurable: true
  62166. });
  62167. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  62168. return "VolumetricLightScatteringPostProcess";
  62169. };
  62170. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  62171. var mesh = subMesh.getMesh();
  62172. // Render this.mesh as default
  62173. if (mesh === this.mesh && mesh.material) {
  62174. return mesh.material.isReady(mesh);
  62175. }
  62176. var defines = [];
  62177. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62178. var material = subMesh.getMaterial();
  62179. // Alpha test
  62180. if (material) {
  62181. if (material.needAlphaTesting()) {
  62182. defines.push("#define ALPHATEST");
  62183. }
  62184. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62185. attribs.push(BABYLON.VertexBuffer.UVKind);
  62186. defines.push("#define UV1");
  62187. }
  62188. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62189. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62190. defines.push("#define UV2");
  62191. }
  62192. }
  62193. // Bones
  62194. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62195. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62196. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62197. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62198. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  62199. }
  62200. else {
  62201. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62202. }
  62203. // Instances
  62204. if (useInstances) {
  62205. defines.push("#define INSTANCES");
  62206. attribs.push("world0");
  62207. attribs.push("world1");
  62208. attribs.push("world2");
  62209. attribs.push("world3");
  62210. }
  62211. // Get correct effect
  62212. var join = defines.join("\n");
  62213. if (this._cachedDefines !== join) {
  62214. this._cachedDefines = join;
  62215. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  62216. }
  62217. return this._volumetricLightScatteringPass.isReady();
  62218. };
  62219. /**
  62220. * Sets the new light position for light scattering effect
  62221. * @param {BABYLON.Vector3} The new custom light position
  62222. */
  62223. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  62224. this.customMeshPosition = position;
  62225. };
  62226. /**
  62227. * Returns the light position for light scattering effect
  62228. * @return {BABYLON.Vector3} The custom light position
  62229. */
  62230. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  62231. return this.customMeshPosition;
  62232. };
  62233. /**
  62234. * Disposes the internal assets and detaches the post-process from the camera
  62235. */
  62236. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  62237. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  62238. if (rttIndex !== -1) {
  62239. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  62240. }
  62241. this._volumetricLightScatteringRTT.dispose();
  62242. _super.prototype.dispose.call(this, camera);
  62243. };
  62244. /**
  62245. * Returns the render target texture used by the post-process
  62246. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  62247. */
  62248. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  62249. return this._volumetricLightScatteringRTT;
  62250. };
  62251. // Private methods
  62252. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  62253. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  62254. return true;
  62255. }
  62256. return false;
  62257. };
  62258. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  62259. var _this = this;
  62260. var engine = scene.getEngine();
  62261. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62262. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62263. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62264. this._volumetricLightScatteringRTT.renderList = null;
  62265. this._volumetricLightScatteringRTT.renderParticles = false;
  62266. var camera = this.getCamera();
  62267. if (camera) {
  62268. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  62269. }
  62270. else {
  62271. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  62272. }
  62273. // Custom render function for submeshes
  62274. var renderSubMesh = function (subMesh) {
  62275. var mesh = subMesh.getRenderingMesh();
  62276. if (_this._meshExcluded(mesh)) {
  62277. return;
  62278. }
  62279. var material = subMesh.getMaterial();
  62280. if (!material) {
  62281. return;
  62282. }
  62283. var scene = mesh.getScene();
  62284. var engine = scene.getEngine();
  62285. // Culling
  62286. engine.setState(material.backFaceCulling);
  62287. // Managing instances
  62288. var batch = mesh._getInstancesRenderList(subMesh._id);
  62289. if (batch.mustReturn) {
  62290. return;
  62291. }
  62292. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  62293. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  62294. var effect = _this._volumetricLightScatteringPass;
  62295. if (mesh === _this.mesh) {
  62296. if (subMesh.effect) {
  62297. effect = subMesh.effect;
  62298. }
  62299. else {
  62300. effect = material.getEffect();
  62301. }
  62302. }
  62303. engine.enableEffect(effect);
  62304. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  62305. if (mesh === _this.mesh) {
  62306. material.bind(mesh.getWorldMatrix(), mesh);
  62307. }
  62308. else {
  62309. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  62310. // Alpha test
  62311. if (material && material.needAlphaTesting()) {
  62312. var alphaTexture = material.getAlphaTestTexture();
  62313. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  62314. if (alphaTexture) {
  62315. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  62316. }
  62317. }
  62318. // Bones
  62319. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62320. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  62321. }
  62322. }
  62323. // Draw
  62324. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  62325. }
  62326. };
  62327. // Render target texture callbacks
  62328. var savedSceneClearColor;
  62329. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  62330. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  62331. savedSceneClearColor = scene.clearColor;
  62332. scene.clearColor = sceneClearColor;
  62333. });
  62334. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  62335. scene.clearColor = savedSceneClearColor;
  62336. });
  62337. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62338. var engine = scene.getEngine();
  62339. var index;
  62340. if (depthOnlySubMeshes.length) {
  62341. engine.setColorWrite(false);
  62342. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62343. renderSubMesh(depthOnlySubMeshes.data[index]);
  62344. }
  62345. engine.setColorWrite(true);
  62346. }
  62347. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62348. renderSubMesh(opaqueSubMeshes.data[index]);
  62349. }
  62350. engine.setAlphaTesting(true);
  62351. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62352. renderSubMesh(alphaTestSubMeshes.data[index]);
  62353. }
  62354. engine.setAlphaTesting(false);
  62355. if (transparentSubMeshes.length) {
  62356. // Sort sub meshes
  62357. for (index = 0; index < transparentSubMeshes.length; index++) {
  62358. var submesh = transparentSubMeshes.data[index];
  62359. var boundingInfo = submesh.getBoundingInfo();
  62360. if (boundingInfo && scene.activeCamera) {
  62361. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  62362. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  62363. }
  62364. }
  62365. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  62366. sortedArray.sort(function (a, b) {
  62367. // Alpha index first
  62368. if (a._alphaIndex > b._alphaIndex) {
  62369. return 1;
  62370. }
  62371. if (a._alphaIndex < b._alphaIndex) {
  62372. return -1;
  62373. }
  62374. // Then distance to camera
  62375. if (a._distanceToCamera < b._distanceToCamera) {
  62376. return 1;
  62377. }
  62378. if (a._distanceToCamera > b._distanceToCamera) {
  62379. return -1;
  62380. }
  62381. return 0;
  62382. });
  62383. // Render sub meshes
  62384. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62385. for (index = 0; index < sortedArray.length; index++) {
  62386. renderSubMesh(sortedArray[index]);
  62387. }
  62388. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62389. }
  62390. };
  62391. };
  62392. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  62393. var transform = scene.getTransformMatrix();
  62394. var meshPosition;
  62395. if (this.useCustomMeshPosition) {
  62396. meshPosition = this.customMeshPosition;
  62397. }
  62398. else if (this.attachedNode) {
  62399. meshPosition = this.attachedNode.position;
  62400. }
  62401. else {
  62402. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  62403. }
  62404. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  62405. this._screenCoordinates.x = pos.x / this._viewPort.width;
  62406. this._screenCoordinates.y = pos.y / this._viewPort.height;
  62407. if (this.invert)
  62408. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  62409. };
  62410. // Static methods
  62411. /**
  62412. * Creates a default mesh for the Volumeric Light Scattering post-process
  62413. * @param {string} The mesh name
  62414. * @param {BABYLON.Scene} The scene where to create the mesh
  62415. * @return {BABYLON.Mesh} the default mesh
  62416. */
  62417. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  62418. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  62419. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  62420. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  62421. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  62422. mesh.material = material;
  62423. return mesh;
  62424. };
  62425. __decorate([
  62426. BABYLON.serializeAsVector3()
  62427. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  62428. __decorate([
  62429. BABYLON.serialize()
  62430. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  62431. __decorate([
  62432. BABYLON.serialize()
  62433. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  62434. __decorate([
  62435. BABYLON.serializeAsMeshReference()
  62436. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  62437. __decorate([
  62438. BABYLON.serialize()
  62439. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  62440. __decorate([
  62441. BABYLON.serialize()
  62442. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  62443. __decorate([
  62444. BABYLON.serialize()
  62445. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  62446. __decorate([
  62447. BABYLON.serialize()
  62448. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  62449. __decorate([
  62450. BABYLON.serialize()
  62451. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  62452. return VolumetricLightScatteringPostProcess;
  62453. }(BABYLON.PostProcess));
  62454. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  62455. })(BABYLON || (BABYLON = {}));
  62456. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  62457. //
  62458. // This post-process allows the modification of rendered colors by using
  62459. // a 'look-up table' (LUT). This effect is also called Color Grading.
  62460. //
  62461. // The object needs to be provided an url to a texture containing the color
  62462. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  62463. // Use an image editing software to tweak the LUT to match your needs.
  62464. //
  62465. // For an example of a color LUT, see here:
  62466. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  62467. // For explanations on color grading, see here:
  62468. // http://udn.epicgames.com/Three/ColorGrading.html
  62469. //
  62470. var BABYLON;
  62471. (function (BABYLON) {
  62472. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  62473. __extends(ColorCorrectionPostProcess, _super);
  62474. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  62475. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  62476. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62477. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  62478. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62479. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62480. _this.onApply = function (effect) {
  62481. effect.setTexture("colorTable", _this._colorTableTexture);
  62482. };
  62483. return _this;
  62484. }
  62485. return ColorCorrectionPostProcess;
  62486. }(BABYLON.PostProcess));
  62487. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  62488. })(BABYLON || (BABYLON = {}));
  62489. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  62490. var BABYLON;
  62491. (function (BABYLON) {
  62492. var TonemappingOperator;
  62493. (function (TonemappingOperator) {
  62494. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  62495. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  62496. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  62497. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  62498. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  62499. ;
  62500. var TonemapPostProcess = /** @class */ (function (_super) {
  62501. __extends(TonemapPostProcess, _super);
  62502. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  62503. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62504. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62505. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  62506. _this._operator = _operator;
  62507. _this.exposureAdjustment = exposureAdjustment;
  62508. var defines = "#define ";
  62509. if (_this._operator === TonemappingOperator.Hable)
  62510. defines += "HABLE_TONEMAPPING";
  62511. else if (_this._operator === TonemappingOperator.Reinhard)
  62512. defines += "REINHARD_TONEMAPPING";
  62513. else if (_this._operator === TonemappingOperator.HejiDawson)
  62514. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  62515. else if (_this._operator === TonemappingOperator.Photographic)
  62516. defines += "PHOTOGRAPHIC_TONEMAPPING";
  62517. //sadly a second call to create the effect.
  62518. _this.updateEffect(defines);
  62519. _this.onApply = function (effect) {
  62520. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  62521. };
  62522. return _this;
  62523. }
  62524. return TonemapPostProcess;
  62525. }(BABYLON.PostProcess));
  62526. BABYLON.TonemapPostProcess = TonemapPostProcess;
  62527. })(BABYLON || (BABYLON = {}));
  62528. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  62529. var BABYLON;
  62530. (function (BABYLON) {
  62531. var DisplayPassPostProcess = /** @class */ (function (_super) {
  62532. __extends(DisplayPassPostProcess, _super);
  62533. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  62534. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  62535. }
  62536. return DisplayPassPostProcess;
  62537. }(BABYLON.PostProcess));
  62538. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  62539. })(BABYLON || (BABYLON = {}));
  62540. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  62541. var BABYLON;
  62542. (function (BABYLON) {
  62543. var HighlightsPostProcess = /** @class */ (function (_super) {
  62544. __extends(HighlightsPostProcess, _super);
  62545. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  62546. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62547. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  62548. }
  62549. return HighlightsPostProcess;
  62550. }(BABYLON.PostProcess));
  62551. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  62552. })(BABYLON || (BABYLON = {}));
  62553. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  62554. var BABYLON;
  62555. (function (BABYLON) {
  62556. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  62557. __extends(ImageProcessingPostProcess, _super);
  62558. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  62559. if (camera === void 0) { camera = null; }
  62560. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62561. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  62562. _this._fromLinearSpace = true;
  62563. /**
  62564. * Defines cache preventing GC.
  62565. */
  62566. _this._defines = {
  62567. IMAGEPROCESSING: false,
  62568. VIGNETTE: false,
  62569. VIGNETTEBLENDMODEMULTIPLY: false,
  62570. VIGNETTEBLENDMODEOPAQUE: false,
  62571. TONEMAPPING: false,
  62572. CONTRAST: false,
  62573. COLORCURVES: false,
  62574. COLORGRADING: false,
  62575. COLORGRADING3D: false,
  62576. FROMLINEARSPACE: false,
  62577. SAMPLER3DGREENDEPTH: false,
  62578. SAMPLER3DBGRMAP: false,
  62579. IMAGEPROCESSINGPOSTPROCESS: false,
  62580. EXPOSURE: false,
  62581. };
  62582. // Setup the configuration as forced by the constructor. This would then not force the
  62583. // scene materials output in linear space and let untouched the default forward pass.
  62584. if (imageProcessingConfiguration) {
  62585. imageProcessingConfiguration.applyByPostProcess = true;
  62586. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  62587. // This will cause the shader to be compiled
  62588. _this.fromLinearSpace = false;
  62589. }
  62590. else {
  62591. _this._attachImageProcessingConfiguration(null, true);
  62592. _this.imageProcessingConfiguration.applyByPostProcess = true;
  62593. }
  62594. _this.onApply = function (effect) {
  62595. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  62596. };
  62597. return _this;
  62598. }
  62599. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  62600. /**
  62601. * Gets the image processing configuration used either in this material.
  62602. */
  62603. get: function () {
  62604. return this._imageProcessingConfiguration;
  62605. },
  62606. /**
  62607. * Sets the Default image processing configuration used either in the this material.
  62608. *
  62609. * If sets to null, the scene one is in use.
  62610. */
  62611. set: function (value) {
  62612. this._attachImageProcessingConfiguration(value);
  62613. },
  62614. enumerable: true,
  62615. configurable: true
  62616. });
  62617. /**
  62618. * Attaches a new image processing configuration to the PBR Material.
  62619. * @param configuration
  62620. */
  62621. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  62622. var _this = this;
  62623. if (doNotBuild === void 0) { doNotBuild = false; }
  62624. if (configuration === this._imageProcessingConfiguration) {
  62625. return;
  62626. }
  62627. // Detaches observer.
  62628. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  62629. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  62630. }
  62631. // Pick the scene configuration if needed.
  62632. if (!configuration) {
  62633. var scene = null;
  62634. var engine = this.getEngine();
  62635. var camera = this.getCamera();
  62636. if (camera) {
  62637. scene = camera.getScene();
  62638. }
  62639. else if (engine && engine.scenes) {
  62640. var scenes = engine.scenes;
  62641. scene = scenes[scenes.length - 1];
  62642. }
  62643. else {
  62644. scene = BABYLON.Engine.LastCreatedScene;
  62645. }
  62646. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  62647. }
  62648. else {
  62649. this._imageProcessingConfiguration = configuration;
  62650. }
  62651. // Attaches observer.
  62652. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  62653. _this._updateParameters();
  62654. });
  62655. // Ensure the effect will be rebuilt.
  62656. if (!doNotBuild) {
  62657. this._updateParameters();
  62658. }
  62659. };
  62660. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  62661. /**
  62662. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  62663. */
  62664. get: function () {
  62665. return this.imageProcessingConfiguration.colorCurves;
  62666. },
  62667. /**
  62668. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  62669. */
  62670. set: function (value) {
  62671. this.imageProcessingConfiguration.colorCurves = value;
  62672. },
  62673. enumerable: true,
  62674. configurable: true
  62675. });
  62676. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  62677. /**
  62678. * Gets wether the color curves effect is enabled.
  62679. */
  62680. get: function () {
  62681. return this.imageProcessingConfiguration.colorCurvesEnabled;
  62682. },
  62683. /**
  62684. * Sets wether the color curves effect is enabled.
  62685. */
  62686. set: function (value) {
  62687. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  62688. },
  62689. enumerable: true,
  62690. configurable: true
  62691. });
  62692. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  62693. /**
  62694. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62695. */
  62696. get: function () {
  62697. return this.imageProcessingConfiguration.colorGradingTexture;
  62698. },
  62699. /**
  62700. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62701. */
  62702. set: function (value) {
  62703. this.imageProcessingConfiguration.colorGradingTexture = value;
  62704. },
  62705. enumerable: true,
  62706. configurable: true
  62707. });
  62708. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  62709. /**
  62710. * Gets wether the color grading effect is enabled.
  62711. */
  62712. get: function () {
  62713. return this.imageProcessingConfiguration.colorGradingEnabled;
  62714. },
  62715. /**
  62716. * Gets wether the color grading effect is enabled.
  62717. */
  62718. set: function (value) {
  62719. this.imageProcessingConfiguration.colorGradingEnabled = value;
  62720. },
  62721. enumerable: true,
  62722. configurable: true
  62723. });
  62724. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  62725. /**
  62726. * Gets exposure used in the effect.
  62727. */
  62728. get: function () {
  62729. return this.imageProcessingConfiguration.exposure;
  62730. },
  62731. /**
  62732. * Sets exposure used in the effect.
  62733. */
  62734. set: function (value) {
  62735. this.imageProcessingConfiguration.exposure = value;
  62736. },
  62737. enumerable: true,
  62738. configurable: true
  62739. });
  62740. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  62741. /**
  62742. * Gets wether tonemapping is enabled or not.
  62743. */
  62744. get: function () {
  62745. return this._imageProcessingConfiguration.toneMappingEnabled;
  62746. },
  62747. /**
  62748. * Sets wether tonemapping is enabled or not
  62749. */
  62750. set: function (value) {
  62751. this._imageProcessingConfiguration.toneMappingEnabled = value;
  62752. },
  62753. enumerable: true,
  62754. configurable: true
  62755. });
  62756. ;
  62757. ;
  62758. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  62759. /**
  62760. * Gets contrast used in the effect.
  62761. */
  62762. get: function () {
  62763. return this.imageProcessingConfiguration.contrast;
  62764. },
  62765. /**
  62766. * Sets contrast used in the effect.
  62767. */
  62768. set: function (value) {
  62769. this.imageProcessingConfiguration.contrast = value;
  62770. },
  62771. enumerable: true,
  62772. configurable: true
  62773. });
  62774. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  62775. /**
  62776. * Gets Vignette stretch size.
  62777. */
  62778. get: function () {
  62779. return this.imageProcessingConfiguration.vignetteStretch;
  62780. },
  62781. /**
  62782. * Sets Vignette stretch size.
  62783. */
  62784. set: function (value) {
  62785. this.imageProcessingConfiguration.vignetteStretch = value;
  62786. },
  62787. enumerable: true,
  62788. configurable: true
  62789. });
  62790. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  62791. /**
  62792. * Gets Vignette centre X Offset.
  62793. */
  62794. get: function () {
  62795. return this.imageProcessingConfiguration.vignetteCentreX;
  62796. },
  62797. /**
  62798. * Sets Vignette centre X Offset.
  62799. */
  62800. set: function (value) {
  62801. this.imageProcessingConfiguration.vignetteCentreX = value;
  62802. },
  62803. enumerable: true,
  62804. configurable: true
  62805. });
  62806. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  62807. /**
  62808. * Gets Vignette centre Y Offset.
  62809. */
  62810. get: function () {
  62811. return this.imageProcessingConfiguration.vignetteCentreY;
  62812. },
  62813. /**
  62814. * Sets Vignette centre Y Offset.
  62815. */
  62816. set: function (value) {
  62817. this.imageProcessingConfiguration.vignetteCentreY = value;
  62818. },
  62819. enumerable: true,
  62820. configurable: true
  62821. });
  62822. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  62823. /**
  62824. * Gets Vignette weight or intensity of the vignette effect.
  62825. */
  62826. get: function () {
  62827. return this.imageProcessingConfiguration.vignetteWeight;
  62828. },
  62829. /**
  62830. * Sets Vignette weight or intensity of the vignette effect.
  62831. */
  62832. set: function (value) {
  62833. this.imageProcessingConfiguration.vignetteWeight = value;
  62834. },
  62835. enumerable: true,
  62836. configurable: true
  62837. });
  62838. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  62839. /**
  62840. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  62841. * if vignetteEnabled is set to true.
  62842. */
  62843. get: function () {
  62844. return this.imageProcessingConfiguration.vignetteColor;
  62845. },
  62846. /**
  62847. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  62848. * if vignetteEnabled is set to true.
  62849. */
  62850. set: function (value) {
  62851. this.imageProcessingConfiguration.vignetteColor = value;
  62852. },
  62853. enumerable: true,
  62854. configurable: true
  62855. });
  62856. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  62857. /**
  62858. * Gets Camera field of view used by the Vignette effect.
  62859. */
  62860. get: function () {
  62861. return this.imageProcessingConfiguration.vignetteCameraFov;
  62862. },
  62863. /**
  62864. * Sets Camera field of view used by the Vignette effect.
  62865. */
  62866. set: function (value) {
  62867. this.imageProcessingConfiguration.vignetteCameraFov = value;
  62868. },
  62869. enumerable: true,
  62870. configurable: true
  62871. });
  62872. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  62873. /**
  62874. * Gets the vignette blend mode allowing different kind of effect.
  62875. */
  62876. get: function () {
  62877. return this.imageProcessingConfiguration.vignetteBlendMode;
  62878. },
  62879. /**
  62880. * Sets the vignette blend mode allowing different kind of effect.
  62881. */
  62882. set: function (value) {
  62883. this.imageProcessingConfiguration.vignetteBlendMode = value;
  62884. },
  62885. enumerable: true,
  62886. configurable: true
  62887. });
  62888. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  62889. /**
  62890. * Gets wether the vignette effect is enabled.
  62891. */
  62892. get: function () {
  62893. return this.imageProcessingConfiguration.vignetteEnabled;
  62894. },
  62895. /**
  62896. * Sets wether the vignette effect is enabled.
  62897. */
  62898. set: function (value) {
  62899. this.imageProcessingConfiguration.vignetteEnabled = value;
  62900. },
  62901. enumerable: true,
  62902. configurable: true
  62903. });
  62904. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  62905. /**
  62906. * Gets wether the input of the processing is in Gamma or Linear Space.
  62907. */
  62908. get: function () {
  62909. return this._fromLinearSpace;
  62910. },
  62911. /**
  62912. * Sets wether the input of the processing is in Gamma or Linear Space.
  62913. */
  62914. set: function (value) {
  62915. if (this._fromLinearSpace === value) {
  62916. return;
  62917. }
  62918. this._fromLinearSpace = value;
  62919. this._updateParameters();
  62920. },
  62921. enumerable: true,
  62922. configurable: true
  62923. });
  62924. ImageProcessingPostProcess.prototype.getClassName = function () {
  62925. return "ImageProcessingPostProcess";
  62926. };
  62927. ImageProcessingPostProcess.prototype._updateParameters = function () {
  62928. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  62929. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  62930. var defines = "";
  62931. for (var define in this._defines) {
  62932. if (this._defines[define]) {
  62933. defines += "#define " + define + ";\r\n";
  62934. }
  62935. }
  62936. var samplers = ["textureSampler"];
  62937. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  62938. var uniforms = ["scale"];
  62939. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  62940. this.updateEffect(defines, uniforms, samplers);
  62941. };
  62942. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  62943. _super.prototype.dispose.call(this, camera);
  62944. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  62945. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  62946. }
  62947. this.imageProcessingConfiguration.applyByPostProcess = false;
  62948. };
  62949. __decorate([
  62950. BABYLON.serialize()
  62951. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  62952. return ImageProcessingPostProcess;
  62953. }(BABYLON.PostProcess));
  62954. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  62955. })(BABYLON || (BABYLON = {}));
  62956. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  62957. var BABYLON;
  62958. (function (BABYLON) {
  62959. var BlurPostProcess = /** @class */ (function (_super) {
  62960. __extends(BlurPostProcess, _super);
  62961. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  62962. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62963. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62964. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  62965. _this.direction = direction;
  62966. _this._packedFloat = false;
  62967. _this.onApplyObservable.add(function (effect) {
  62968. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  62969. });
  62970. _this.kernel = kernel;
  62971. return _this;
  62972. }
  62973. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  62974. /**
  62975. * Gets the length in pixels of the blur sample region
  62976. */
  62977. get: function () {
  62978. return this._idealKernel;
  62979. },
  62980. /**
  62981. * Sets the length in pixels of the blur sample region
  62982. */
  62983. set: function (v) {
  62984. if (this._idealKernel === v) {
  62985. return;
  62986. }
  62987. v = Math.max(v, 1);
  62988. this._idealKernel = v;
  62989. this._kernel = this._nearestBestKernel(v);
  62990. this._updateParameters();
  62991. },
  62992. enumerable: true,
  62993. configurable: true
  62994. });
  62995. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  62996. /**
  62997. * Gets wether or not the blur is unpacking/repacking floats
  62998. */
  62999. get: function () {
  63000. return this._packedFloat;
  63001. },
  63002. /**
  63003. * Sets wether or not the blur needs to unpack/repack floats
  63004. */
  63005. set: function (v) {
  63006. if (this._packedFloat === v) {
  63007. return;
  63008. }
  63009. this._packedFloat = v;
  63010. this._updateParameters();
  63011. },
  63012. enumerable: true,
  63013. configurable: true
  63014. });
  63015. BlurPostProcess.prototype._updateParameters = function () {
  63016. // Generate sampling offsets and weights
  63017. var N = this._kernel;
  63018. var centerIndex = (N - 1) / 2;
  63019. // Generate Gaussian sampling weights over kernel
  63020. var offsets = [];
  63021. var weights = [];
  63022. var totalWeight = 0;
  63023. for (var i = 0; i < N; i++) {
  63024. var u = i / (N - 1);
  63025. var w = this._gaussianWeight(u * 2.0 - 1);
  63026. offsets[i] = (i - centerIndex);
  63027. weights[i] = w;
  63028. totalWeight += w;
  63029. }
  63030. // Normalize weights
  63031. for (var i = 0; i < weights.length; i++) {
  63032. weights[i] /= totalWeight;
  63033. }
  63034. // Optimize: combine samples to take advantage of hardware linear sampling
  63035. // Walk from left to center, combining pairs (symmetrically)
  63036. var linearSamplingWeights = [];
  63037. var linearSamplingOffsets = [];
  63038. var linearSamplingMap = [];
  63039. for (var i = 0; i <= centerIndex; i += 2) {
  63040. var j = Math.min(i + 1, Math.floor(centerIndex));
  63041. var singleCenterSample = i === j;
  63042. if (singleCenterSample) {
  63043. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  63044. }
  63045. else {
  63046. var sharedCell = j === centerIndex;
  63047. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  63048. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  63049. if (offsetLinear === 0) {
  63050. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  63051. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  63052. }
  63053. else {
  63054. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  63055. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  63056. }
  63057. }
  63058. }
  63059. for (var i = 0; i < linearSamplingMap.length; i++) {
  63060. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  63061. linearSamplingWeights[i] = linearSamplingMap[i].w;
  63062. }
  63063. // Replace with optimized
  63064. offsets = linearSamplingOffsets;
  63065. weights = linearSamplingWeights;
  63066. // Generate shaders
  63067. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  63068. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  63069. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  63070. var defines = "";
  63071. for (var i = 0; i < varyingCount; i++) {
  63072. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  63073. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  63074. }
  63075. var depCount = 0;
  63076. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  63077. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  63078. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  63079. depCount++;
  63080. }
  63081. if (this.packedFloat) {
  63082. defines += "#define PACKEDFLOAT 1";
  63083. }
  63084. this.updateEffect(defines, null, null, {
  63085. varyingCount: varyingCount,
  63086. depCount: depCount
  63087. });
  63088. };
  63089. /**
  63090. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  63091. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  63092. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  63093. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  63094. * The gaps between physical kernels are compensated for in the weighting of the samples
  63095. * @param idealKernel Ideal blur kernel.
  63096. * @return Nearest best kernel.
  63097. */
  63098. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  63099. var v = Math.round(idealKernel);
  63100. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  63101. var k = _a[_i];
  63102. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  63103. return Math.max(k, 3);
  63104. }
  63105. }
  63106. return Math.max(v, 3);
  63107. };
  63108. /**
  63109. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  63110. * @param x The point on the Gaussian distribution to sample.
  63111. * @return the value of the Gaussian function at x.
  63112. */
  63113. BlurPostProcess.prototype._gaussianWeight = function (x) {
  63114. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  63115. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  63116. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  63117. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  63118. // truncated at around 1.3% of peak strength.
  63119. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  63120. var sigma = (1 / 3);
  63121. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  63122. var exponent = -((x * x) / (2.0 * sigma * sigma));
  63123. var weight = (1.0 / denominator) * Math.exp(exponent);
  63124. return weight;
  63125. };
  63126. /**
  63127. * Generates a string that can be used as a floating point number in GLSL.
  63128. * @param x Value to print.
  63129. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  63130. * @return GLSL float string.
  63131. */
  63132. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  63133. if (decimalFigures === void 0) { decimalFigures = 8; }
  63134. return x.toFixed(decimalFigures).replace(/0+$/, '');
  63135. };
  63136. return BlurPostProcess;
  63137. }(BABYLON.PostProcess));
  63138. BABYLON.BlurPostProcess = BlurPostProcess;
  63139. })(BABYLON || (BABYLON = {}));
  63140. //# sourceMappingURL=babylon.blurPostProcess.js.map
  63141. var BABYLON;
  63142. (function (BABYLON) {
  63143. var Bone = /** @class */ (function (_super) {
  63144. __extends(Bone, _super);
  63145. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  63146. if (parentBone === void 0) { parentBone = null; }
  63147. if (localMatrix === void 0) { localMatrix = null; }
  63148. if (restPose === void 0) { restPose = null; }
  63149. if (baseMatrix === void 0) { baseMatrix = null; }
  63150. if (index === void 0) { index = null; }
  63151. var _this = _super.call(this, name, skeleton.getScene()) || this;
  63152. _this.name = name;
  63153. _this.children = new Array();
  63154. _this.animations = new Array();
  63155. // Set this value to map this bone to a different index in the transform matrices.
  63156. // Set this value to -1 to exclude the bone from the transform matrices.
  63157. _this._index = null;
  63158. _this._worldTransform = new BABYLON.Matrix();
  63159. _this._absoluteTransform = new BABYLON.Matrix();
  63160. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  63161. _this._scaleMatrix = BABYLON.Matrix.Identity();
  63162. _this._scaleVector = BABYLON.Vector3.One();
  63163. _this._negateScaleChildren = BABYLON.Vector3.One();
  63164. _this._scalingDeterminant = 1;
  63165. _this._skeleton = skeleton;
  63166. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  63167. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  63168. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  63169. _this._index = index;
  63170. skeleton.bones.push(_this);
  63171. _this.setParent(parentBone, false);
  63172. _this._updateDifferenceMatrix();
  63173. return _this;
  63174. }
  63175. Object.defineProperty(Bone.prototype, "_matrix", {
  63176. get: function () {
  63177. return this._localMatrix;
  63178. },
  63179. set: function (val) {
  63180. if (this._localMatrix) {
  63181. this._localMatrix.copyFrom(val);
  63182. }
  63183. else {
  63184. this._localMatrix = val;
  63185. }
  63186. },
  63187. enumerable: true,
  63188. configurable: true
  63189. });
  63190. // Members
  63191. Bone.prototype.getSkeleton = function () {
  63192. return this._skeleton;
  63193. };
  63194. Bone.prototype.getParent = function () {
  63195. return this._parent;
  63196. };
  63197. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  63198. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  63199. if (this._parent === parent) {
  63200. return;
  63201. }
  63202. if (this._parent) {
  63203. var index = this._parent.children.indexOf(this);
  63204. if (index !== -1) {
  63205. this._parent.children.splice(index, 1);
  63206. }
  63207. }
  63208. this._parent = parent;
  63209. if (this._parent) {
  63210. this._parent.children.push(this);
  63211. }
  63212. if (updateDifferenceMatrix) {
  63213. this._updateDifferenceMatrix();
  63214. }
  63215. };
  63216. Bone.prototype.getLocalMatrix = function () {
  63217. return this._localMatrix;
  63218. };
  63219. Bone.prototype.getBaseMatrix = function () {
  63220. return this._baseMatrix;
  63221. };
  63222. Bone.prototype.getRestPose = function () {
  63223. return this._restPose;
  63224. };
  63225. Bone.prototype.returnToRest = function () {
  63226. this.updateMatrix(this._restPose.clone());
  63227. };
  63228. Bone.prototype.getWorldMatrix = function () {
  63229. return this._worldTransform;
  63230. };
  63231. Bone.prototype.getInvertedAbsoluteTransform = function () {
  63232. return this._invertedAbsoluteTransform;
  63233. };
  63234. Bone.prototype.getAbsoluteTransform = function () {
  63235. return this._absoluteTransform;
  63236. };
  63237. Object.defineProperty(Bone.prototype, "position", {
  63238. // Properties (matches AbstractMesh properties)
  63239. get: function () {
  63240. return this.getPosition();
  63241. },
  63242. set: function (newPosition) {
  63243. this.setPosition(newPosition);
  63244. },
  63245. enumerable: true,
  63246. configurable: true
  63247. });
  63248. Object.defineProperty(Bone.prototype, "rotation", {
  63249. get: function () {
  63250. return this.getRotation();
  63251. },
  63252. set: function (newRotation) {
  63253. this.setRotation(newRotation);
  63254. },
  63255. enumerable: true,
  63256. configurable: true
  63257. });
  63258. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  63259. get: function () {
  63260. return this.getRotationQuaternion();
  63261. },
  63262. set: function (newRotation) {
  63263. this.setRotationQuaternion(newRotation);
  63264. },
  63265. enumerable: true,
  63266. configurable: true
  63267. });
  63268. Object.defineProperty(Bone.prototype, "scaling", {
  63269. get: function () {
  63270. return this.getScale();
  63271. },
  63272. set: function (newScaling) {
  63273. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  63274. },
  63275. enumerable: true,
  63276. configurable: true
  63277. });
  63278. // Methods
  63279. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  63280. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  63281. this._baseMatrix = matrix.clone();
  63282. this._localMatrix = matrix.clone();
  63283. this._skeleton._markAsDirty();
  63284. if (updateDifferenceMatrix) {
  63285. this._updateDifferenceMatrix();
  63286. }
  63287. };
  63288. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  63289. if (!rootMatrix) {
  63290. rootMatrix = this._baseMatrix;
  63291. }
  63292. if (this._parent) {
  63293. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  63294. }
  63295. else {
  63296. this._absoluteTransform.copyFrom(rootMatrix);
  63297. }
  63298. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  63299. for (var index = 0; index < this.children.length; index++) {
  63300. this.children[index]._updateDifferenceMatrix();
  63301. }
  63302. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  63303. };
  63304. Bone.prototype.markAsDirty = function () {
  63305. this._currentRenderId++;
  63306. this._skeleton._markAsDirty();
  63307. };
  63308. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  63309. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  63310. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  63311. // all animation may be coming from a library skeleton, so may need to create animation
  63312. if (this.animations.length === 0) {
  63313. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  63314. this.animations[0].setKeys([]);
  63315. }
  63316. // get animation info / verify there is such a range from the source bone
  63317. var sourceRange = source.animations[0].getRange(rangeName);
  63318. if (!sourceRange) {
  63319. return false;
  63320. }
  63321. var from = sourceRange.from;
  63322. var to = sourceRange.to;
  63323. var sourceKeys = source.animations[0].getKeys();
  63324. // rescaling prep
  63325. var sourceBoneLength = source.length;
  63326. var sourceParent = source.getParent();
  63327. var parent = this.getParent();
  63328. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  63329. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  63330. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  63331. var destKeys = this.animations[0].getKeys();
  63332. // loop vars declaration
  63333. var orig;
  63334. var origTranslation;
  63335. var mat;
  63336. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  63337. orig = sourceKeys[key];
  63338. if (orig.frame >= from && orig.frame <= to) {
  63339. if (rescaleAsRequired) {
  63340. mat = orig.value.clone();
  63341. // scale based on parent ratio, when bone has parent
  63342. if (parentScalingReqd) {
  63343. origTranslation = mat.getTranslation();
  63344. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  63345. // scale based on skeleton dimension ratio when root bone, and value is passed
  63346. }
  63347. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  63348. origTranslation = mat.getTranslation();
  63349. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  63350. // use original when root bone, and no data for skelDimensionsRatio
  63351. }
  63352. else {
  63353. mat = orig.value;
  63354. }
  63355. }
  63356. else {
  63357. mat = orig.value;
  63358. }
  63359. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  63360. }
  63361. }
  63362. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  63363. return true;
  63364. };
  63365. /**
  63366. * Translate the bone in local or world space.
  63367. * @param vec The amount to translate the bone.
  63368. * @param space The space that the translation is in.
  63369. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63370. */
  63371. Bone.prototype.translate = function (vec, space, mesh) {
  63372. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63373. var lm = this.getLocalMatrix();
  63374. if (space == BABYLON.Space.LOCAL) {
  63375. lm.m[12] += vec.x;
  63376. lm.m[13] += vec.y;
  63377. lm.m[14] += vec.z;
  63378. }
  63379. else {
  63380. var wm = null;
  63381. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63382. if (mesh) {
  63383. wm = mesh.getWorldMatrix();
  63384. }
  63385. this._skeleton.computeAbsoluteTransforms();
  63386. var tmat = Bone._tmpMats[0];
  63387. var tvec = Bone._tmpVecs[0];
  63388. if (this._parent) {
  63389. if (mesh && wm) {
  63390. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63391. tmat.multiplyToRef(wm, tmat);
  63392. }
  63393. else {
  63394. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63395. }
  63396. }
  63397. tmat.m[12] = 0;
  63398. tmat.m[13] = 0;
  63399. tmat.m[14] = 0;
  63400. tmat.invert();
  63401. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  63402. lm.m[12] += tvec.x;
  63403. lm.m[13] += tvec.y;
  63404. lm.m[14] += tvec.z;
  63405. }
  63406. this.markAsDirty();
  63407. };
  63408. /**
  63409. * Set the postion of the bone in local or world space.
  63410. * @param position The position to set the bone.
  63411. * @param space The space that the position is in.
  63412. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63413. */
  63414. Bone.prototype.setPosition = function (position, space, mesh) {
  63415. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63416. var lm = this.getLocalMatrix();
  63417. if (space == BABYLON.Space.LOCAL) {
  63418. lm.m[12] = position.x;
  63419. lm.m[13] = position.y;
  63420. lm.m[14] = position.z;
  63421. }
  63422. else {
  63423. var wm = null;
  63424. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63425. if (mesh) {
  63426. wm = mesh.getWorldMatrix();
  63427. }
  63428. this._skeleton.computeAbsoluteTransforms();
  63429. var tmat = Bone._tmpMats[0];
  63430. var vec = Bone._tmpVecs[0];
  63431. if (this._parent) {
  63432. if (mesh && wm) {
  63433. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63434. tmat.multiplyToRef(wm, tmat);
  63435. }
  63436. else {
  63437. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63438. }
  63439. }
  63440. tmat.invert();
  63441. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  63442. lm.m[12] = vec.x;
  63443. lm.m[13] = vec.y;
  63444. lm.m[14] = vec.z;
  63445. }
  63446. this.markAsDirty();
  63447. };
  63448. /**
  63449. * Set the absolute postion of the bone (world space).
  63450. * @param position The position to set the bone.
  63451. * @param mesh The mesh that this bone is attached to.
  63452. */
  63453. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  63454. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  63455. };
  63456. /**
  63457. * Set the scale of the bone on the x, y and z axes.
  63458. * @param x The scale of the bone on the x axis.
  63459. * @param x The scale of the bone on the y axis.
  63460. * @param z The scale of the bone on the z axis.
  63461. * @param scaleChildren Set this to true if children of the bone should be scaled.
  63462. */
  63463. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  63464. if (scaleChildren === void 0) { scaleChildren = false; }
  63465. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  63466. if (!scaleChildren) {
  63467. this._negateScaleChildren.x = 1 / x;
  63468. this._negateScaleChildren.y = 1 / y;
  63469. this._negateScaleChildren.z = 1 / z;
  63470. }
  63471. this._syncScaleVector();
  63472. }
  63473. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  63474. };
  63475. /**
  63476. * Scale the bone on the x, y and z axes.
  63477. * @param x The amount to scale the bone on the x axis.
  63478. * @param x The amount to scale the bone on the y axis.
  63479. * @param z The amount to scale the bone on the z axis.
  63480. * @param scaleChildren Set this to true if children of the bone should be scaled.
  63481. */
  63482. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  63483. if (scaleChildren === void 0) { scaleChildren = false; }
  63484. var locMat = this.getLocalMatrix();
  63485. var origLocMat = Bone._tmpMats[0];
  63486. origLocMat.copyFrom(locMat);
  63487. var origLocMatInv = Bone._tmpMats[1];
  63488. origLocMatInv.copyFrom(origLocMat);
  63489. origLocMatInv.invert();
  63490. var scaleMat = Bone._tmpMats[2];
  63491. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  63492. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  63493. this._scaleVector.x *= x;
  63494. this._scaleVector.y *= y;
  63495. this._scaleVector.z *= z;
  63496. locMat.multiplyToRef(origLocMatInv, locMat);
  63497. locMat.multiplyToRef(scaleMat, locMat);
  63498. locMat.multiplyToRef(origLocMat, locMat);
  63499. var parent = this.getParent();
  63500. if (parent) {
  63501. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  63502. }
  63503. else {
  63504. this.getAbsoluteTransform().copyFrom(locMat);
  63505. }
  63506. var len = this.children.length;
  63507. scaleMat.invert();
  63508. for (var i = 0; i < len; i++) {
  63509. var child = this.children[i];
  63510. var cm = child.getLocalMatrix();
  63511. cm.multiplyToRef(scaleMat, cm);
  63512. var lm = child.getLocalMatrix();
  63513. lm.m[12] *= x;
  63514. lm.m[13] *= y;
  63515. lm.m[14] *= z;
  63516. }
  63517. this.computeAbsoluteTransforms();
  63518. if (scaleChildren) {
  63519. for (var i = 0; i < len; i++) {
  63520. this.children[i].scale(x, y, z, scaleChildren);
  63521. }
  63522. }
  63523. this.markAsDirty();
  63524. };
  63525. /**
  63526. * Set the yaw, pitch, and roll of the bone in local or world space.
  63527. * @param yaw The rotation of the bone on the y axis.
  63528. * @param pitch The rotation of the bone on the x axis.
  63529. * @param roll The rotation of the bone on the z axis.
  63530. * @param space The space that the axes of rotation are in.
  63531. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63532. */
  63533. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  63534. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63535. var rotMat = Bone._tmpMats[0];
  63536. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  63537. var rotMatInv = Bone._tmpMats[1];
  63538. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63539. rotMatInv.multiplyToRef(rotMat, rotMat);
  63540. this._rotateWithMatrix(rotMat, space, mesh);
  63541. };
  63542. /**
  63543. * Rotate the bone on an axis in local or world space.
  63544. * @param axis The axis to rotate the bone on.
  63545. * @param amount The amount to rotate the bone.
  63546. * @param space The space that the axis is in.
  63547. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63548. */
  63549. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  63550. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63551. var rmat = Bone._tmpMats[0];
  63552. rmat.m[12] = 0;
  63553. rmat.m[13] = 0;
  63554. rmat.m[14] = 0;
  63555. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  63556. this._rotateWithMatrix(rmat, space, mesh);
  63557. };
  63558. /**
  63559. * Set the rotation of the bone to a particular axis angle in local or world space.
  63560. * @param axis The axis to rotate the bone on.
  63561. * @param angle The angle that the bone should be rotated to.
  63562. * @param space The space that the axis is in.
  63563. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63564. */
  63565. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  63566. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63567. var rotMat = Bone._tmpMats[0];
  63568. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  63569. var rotMatInv = Bone._tmpMats[1];
  63570. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63571. rotMatInv.multiplyToRef(rotMat, rotMat);
  63572. this._rotateWithMatrix(rotMat, space, mesh);
  63573. };
  63574. /**
  63575. * Set the euler rotation of the bone in local of world space.
  63576. * @param rotation The euler rotation that the bone should be set to.
  63577. * @param space The space that the rotation is in.
  63578. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63579. */
  63580. Bone.prototype.setRotation = function (rotation, space, mesh) {
  63581. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63582. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  63583. };
  63584. /**
  63585. * Set the quaternion rotation of the bone in local of world space.
  63586. * @param quat The quaternion rotation that the bone should be set to.
  63587. * @param space The space that the rotation is in.
  63588. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63589. */
  63590. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  63591. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63592. var rotMatInv = Bone._tmpMats[0];
  63593. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63594. var rotMat = Bone._tmpMats[1];
  63595. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  63596. rotMatInv.multiplyToRef(rotMat, rotMat);
  63597. this._rotateWithMatrix(rotMat, space, mesh);
  63598. };
  63599. /**
  63600. * Set the rotation matrix of the bone in local of world space.
  63601. * @param rotMat The rotation matrix that the bone should be set to.
  63602. * @param space The space that the rotation is in.
  63603. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63604. */
  63605. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  63606. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63607. var rotMatInv = Bone._tmpMats[0];
  63608. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63609. var rotMat2 = Bone._tmpMats[1];
  63610. rotMat2.copyFrom(rotMat);
  63611. rotMatInv.multiplyToRef(rotMat, rotMat2);
  63612. this._rotateWithMatrix(rotMat2, space, mesh);
  63613. };
  63614. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  63615. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63616. var lmat = this.getLocalMatrix();
  63617. var lx = lmat.m[12];
  63618. var ly = lmat.m[13];
  63619. var lz = lmat.m[14];
  63620. var parent = this.getParent();
  63621. var parentScale = Bone._tmpMats[3];
  63622. var parentScaleInv = Bone._tmpMats[4];
  63623. if (parent) {
  63624. if (space == BABYLON.Space.WORLD) {
  63625. if (mesh) {
  63626. parentScale.copyFrom(mesh.getWorldMatrix());
  63627. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  63628. }
  63629. else {
  63630. parentScale.copyFrom(parent.getAbsoluteTransform());
  63631. }
  63632. }
  63633. else {
  63634. parentScale = parent._scaleMatrix;
  63635. }
  63636. parentScaleInv.copyFrom(parentScale);
  63637. parentScaleInv.invert();
  63638. lmat.multiplyToRef(parentScale, lmat);
  63639. lmat.multiplyToRef(rmat, lmat);
  63640. lmat.multiplyToRef(parentScaleInv, lmat);
  63641. }
  63642. else {
  63643. if (space == BABYLON.Space.WORLD && mesh) {
  63644. parentScale.copyFrom(mesh.getWorldMatrix());
  63645. parentScaleInv.copyFrom(parentScale);
  63646. parentScaleInv.invert();
  63647. lmat.multiplyToRef(parentScale, lmat);
  63648. lmat.multiplyToRef(rmat, lmat);
  63649. lmat.multiplyToRef(parentScaleInv, lmat);
  63650. }
  63651. else {
  63652. lmat.multiplyToRef(rmat, lmat);
  63653. }
  63654. }
  63655. lmat.m[12] = lx;
  63656. lmat.m[13] = ly;
  63657. lmat.m[14] = lz;
  63658. this.computeAbsoluteTransforms();
  63659. this.markAsDirty();
  63660. };
  63661. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  63662. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63663. if (space == BABYLON.Space.WORLD) {
  63664. var scaleMatrix = Bone._tmpMats[2];
  63665. scaleMatrix.copyFrom(this._scaleMatrix);
  63666. rotMatInv.copyFrom(this.getAbsoluteTransform());
  63667. if (mesh) {
  63668. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  63669. var meshScale = Bone._tmpMats[3];
  63670. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  63671. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  63672. }
  63673. rotMatInv.invert();
  63674. scaleMatrix.m[0] *= this._scalingDeterminant;
  63675. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63676. }
  63677. else {
  63678. rotMatInv.copyFrom(this.getLocalMatrix());
  63679. rotMatInv.invert();
  63680. var scaleMatrix = Bone._tmpMats[2];
  63681. scaleMatrix.copyFrom(this._scaleMatrix);
  63682. if (this._parent) {
  63683. var pscaleMatrix = Bone._tmpMats[3];
  63684. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  63685. pscaleMatrix.invert();
  63686. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  63687. }
  63688. else {
  63689. scaleMatrix.m[0] *= this._scalingDeterminant;
  63690. }
  63691. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63692. }
  63693. };
  63694. /**
  63695. * Get the scale of the bone
  63696. * @returns the scale of the bone
  63697. */
  63698. Bone.prototype.getScale = function () {
  63699. return this._scaleVector.clone();
  63700. };
  63701. /**
  63702. * Copy the scale of the bone to a vector3.
  63703. * @param result The vector3 to copy the scale to
  63704. */
  63705. Bone.prototype.getScaleToRef = function (result) {
  63706. result.copyFrom(this._scaleVector);
  63707. };
  63708. /**
  63709. * Get the position of the bone in local or world space.
  63710. * @param space The space that the returned position is in.
  63711. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63712. * @returns The position of the bone
  63713. */
  63714. Bone.prototype.getPosition = function (space, mesh) {
  63715. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63716. if (mesh === void 0) { mesh = null; }
  63717. var pos = BABYLON.Vector3.Zero();
  63718. this.getPositionToRef(space, mesh, pos);
  63719. return pos;
  63720. };
  63721. /**
  63722. * Copy the position of the bone to a vector3 in local or world space.
  63723. * @param space The space that the returned position is in.
  63724. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63725. * @param result The vector3 to copy the position to.
  63726. */
  63727. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  63728. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63729. if (space == BABYLON.Space.LOCAL) {
  63730. var lm = this.getLocalMatrix();
  63731. result.x = lm.m[12];
  63732. result.y = lm.m[13];
  63733. result.z = lm.m[14];
  63734. }
  63735. else {
  63736. var wm = null;
  63737. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63738. if (mesh) {
  63739. wm = mesh.getWorldMatrix();
  63740. }
  63741. this._skeleton.computeAbsoluteTransforms();
  63742. var tmat = Bone._tmpMats[0];
  63743. if (mesh && wm) {
  63744. tmat.copyFrom(this.getAbsoluteTransform());
  63745. tmat.multiplyToRef(wm, tmat);
  63746. }
  63747. else {
  63748. tmat = this.getAbsoluteTransform();
  63749. }
  63750. result.x = tmat.m[12];
  63751. result.y = tmat.m[13];
  63752. result.z = tmat.m[14];
  63753. }
  63754. };
  63755. /**
  63756. * Get the absolute position of the bone (world space).
  63757. * @param mesh The mesh that this bone is attached to.
  63758. * @returns The absolute position of the bone
  63759. */
  63760. Bone.prototype.getAbsolutePosition = function (mesh) {
  63761. if (mesh === void 0) { mesh = null; }
  63762. var pos = BABYLON.Vector3.Zero();
  63763. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  63764. return pos;
  63765. };
  63766. /**
  63767. * Copy the absolute position of the bone (world space) to the result param.
  63768. * @param mesh The mesh that this bone is attached to.
  63769. * @param result The vector3 to copy the absolute position to.
  63770. */
  63771. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  63772. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  63773. };
  63774. /**
  63775. * Compute the absolute transforms of this bone and its children.
  63776. */
  63777. Bone.prototype.computeAbsoluteTransforms = function () {
  63778. if (this._parent) {
  63779. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  63780. }
  63781. else {
  63782. this._absoluteTransform.copyFrom(this._localMatrix);
  63783. var poseMatrix = this._skeleton.getPoseMatrix();
  63784. if (poseMatrix) {
  63785. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  63786. }
  63787. }
  63788. var children = this.children;
  63789. var len = children.length;
  63790. for (var i = 0; i < len; i++) {
  63791. children[i].computeAbsoluteTransforms();
  63792. }
  63793. };
  63794. Bone.prototype._syncScaleVector = function () {
  63795. var lm = this.getLocalMatrix();
  63796. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  63797. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  63798. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  63799. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  63800. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  63801. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  63802. this._scaleVector.x = xs * Math.sqrt(xsq);
  63803. this._scaleVector.y = ys * Math.sqrt(ysq);
  63804. this._scaleVector.z = zs * Math.sqrt(zsq);
  63805. if (this._parent) {
  63806. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  63807. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  63808. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  63809. }
  63810. 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);
  63811. };
  63812. /**
  63813. * Get the world direction from an axis that is in the local space of the bone.
  63814. * @param localAxis The local direction that is used to compute the world direction.
  63815. * @param mesh The mesh that this bone is attached to.
  63816. * @returns The world direction
  63817. */
  63818. Bone.prototype.getDirection = function (localAxis, mesh) {
  63819. if (mesh === void 0) { mesh = null; }
  63820. var result = BABYLON.Vector3.Zero();
  63821. this.getDirectionToRef(localAxis, mesh, result);
  63822. return result;
  63823. };
  63824. /**
  63825. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  63826. * @param localAxis The local direction that is used to compute the world direction.
  63827. * @param mesh The mesh that this bone is attached to.
  63828. * @param result The vector3 that the world direction will be copied to.
  63829. */
  63830. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  63831. if (mesh === void 0) { mesh = null; }
  63832. var wm = null;
  63833. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63834. if (mesh) {
  63835. wm = mesh.getWorldMatrix();
  63836. }
  63837. this._skeleton.computeAbsoluteTransforms();
  63838. var mat = Bone._tmpMats[0];
  63839. mat.copyFrom(this.getAbsoluteTransform());
  63840. if (mesh && wm) {
  63841. mat.multiplyToRef(wm, mat);
  63842. }
  63843. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  63844. result.normalize();
  63845. };
  63846. /**
  63847. * Get the euler rotation of the bone in local or world space.
  63848. * @param space The space that the rotation should be in.
  63849. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63850. * @returns The euler rotation
  63851. */
  63852. Bone.prototype.getRotation = function (space, mesh) {
  63853. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63854. if (mesh === void 0) { mesh = null; }
  63855. var result = BABYLON.Vector3.Zero();
  63856. this.getRotationToRef(space, mesh, result);
  63857. return result;
  63858. };
  63859. /**
  63860. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  63861. * @param space The space that the rotation should be in.
  63862. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63863. * @param result The vector3 that the rotation should be copied to.
  63864. */
  63865. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  63866. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63867. if (mesh === void 0) { mesh = null; }
  63868. var quat = Bone._tmpQuat;
  63869. this.getRotationQuaternionToRef(space, mesh, quat);
  63870. quat.toEulerAnglesToRef(result);
  63871. };
  63872. /**
  63873. * Get the quaternion rotation of the bone in either local or world space.
  63874. * @param space The space that the rotation should be in.
  63875. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63876. * @returns The quaternion rotation
  63877. */
  63878. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  63879. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63880. if (mesh === void 0) { mesh = null; }
  63881. var result = BABYLON.Quaternion.Identity();
  63882. this.getRotationQuaternionToRef(space, mesh, result);
  63883. return result;
  63884. };
  63885. /**
  63886. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  63887. * @param space The space that the rotation should be in.
  63888. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63889. * @param result The quaternion that the rotation should be copied to.
  63890. */
  63891. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  63892. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63893. if (mesh === void 0) { mesh = null; }
  63894. if (space == BABYLON.Space.LOCAL) {
  63895. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  63896. }
  63897. else {
  63898. var mat = Bone._tmpMats[0];
  63899. var amat = this.getAbsoluteTransform();
  63900. if (mesh) {
  63901. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  63902. }
  63903. else {
  63904. mat.copyFrom(amat);
  63905. }
  63906. mat.m[0] *= this._scalingDeterminant;
  63907. mat.m[1] *= this._scalingDeterminant;
  63908. mat.m[2] *= this._scalingDeterminant;
  63909. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  63910. }
  63911. };
  63912. /**
  63913. * Get the rotation matrix of the bone in local or world space.
  63914. * @param space The space that the rotation should be in.
  63915. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63916. * @returns The rotation matrix
  63917. */
  63918. Bone.prototype.getRotationMatrix = function (space, mesh) {
  63919. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63920. var result = BABYLON.Matrix.Identity();
  63921. this.getRotationMatrixToRef(space, mesh, result);
  63922. return result;
  63923. };
  63924. /**
  63925. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  63926. * @param space The space that the rotation should be in.
  63927. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63928. * @param result The quaternion that the rotation should be copied to.
  63929. */
  63930. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  63931. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63932. if (space == BABYLON.Space.LOCAL) {
  63933. this.getLocalMatrix().getRotationMatrixToRef(result);
  63934. }
  63935. else {
  63936. var mat = Bone._tmpMats[0];
  63937. var amat = this.getAbsoluteTransform();
  63938. if (mesh) {
  63939. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  63940. }
  63941. else {
  63942. mat.copyFrom(amat);
  63943. }
  63944. mat.m[0] *= this._scalingDeterminant;
  63945. mat.m[1] *= this._scalingDeterminant;
  63946. mat.m[2] *= this._scalingDeterminant;
  63947. mat.getRotationMatrixToRef(result);
  63948. }
  63949. };
  63950. /**
  63951. * Get the world position of a point that is in the local space of the bone.
  63952. * @param position The local position
  63953. * @param mesh The mesh that this bone is attached to.
  63954. * @returns The world position
  63955. */
  63956. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  63957. if (mesh === void 0) { mesh = null; }
  63958. var result = BABYLON.Vector3.Zero();
  63959. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  63960. return result;
  63961. };
  63962. /**
  63963. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  63964. * @param position The local position
  63965. * @param mesh The mesh that this bone is attached to.
  63966. * @param result The vector3 that the world position should be copied to.
  63967. */
  63968. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  63969. if (mesh === void 0) { mesh = null; }
  63970. var wm = null;
  63971. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63972. if (mesh) {
  63973. wm = mesh.getWorldMatrix();
  63974. }
  63975. this._skeleton.computeAbsoluteTransforms();
  63976. var tmat = Bone._tmpMats[0];
  63977. if (mesh && wm) {
  63978. tmat.copyFrom(this.getAbsoluteTransform());
  63979. tmat.multiplyToRef(wm, tmat);
  63980. }
  63981. else {
  63982. tmat = this.getAbsoluteTransform();
  63983. }
  63984. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  63985. };
  63986. /**
  63987. * Get the local position of a point that is in world space.
  63988. * @param position The world position
  63989. * @param mesh The mesh that this bone is attached to.
  63990. * @returns The local position
  63991. */
  63992. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  63993. if (mesh === void 0) { mesh = null; }
  63994. var result = BABYLON.Vector3.Zero();
  63995. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  63996. return result;
  63997. };
  63998. /**
  63999. * Get the local position of a point that is in world space and copy it to the result param.
  64000. * @param position The world position
  64001. * @param mesh The mesh that this bone is attached to.
  64002. * @param result The vector3 that the local position should be copied to.
  64003. */
  64004. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  64005. if (mesh === void 0) { mesh = null; }
  64006. var wm = null;
  64007. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  64008. if (mesh) {
  64009. wm = mesh.getWorldMatrix();
  64010. }
  64011. this._skeleton.computeAbsoluteTransforms();
  64012. var tmat = Bone._tmpMats[0];
  64013. tmat.copyFrom(this.getAbsoluteTransform());
  64014. if (mesh && wm) {
  64015. tmat.multiplyToRef(wm, tmat);
  64016. }
  64017. tmat.invert();
  64018. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  64019. };
  64020. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64021. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  64022. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64023. return Bone;
  64024. }(BABYLON.Node));
  64025. BABYLON.Bone = Bone;
  64026. })(BABYLON || (BABYLON = {}));
  64027. //# sourceMappingURL=babylon.bone.js.map
  64028. var BABYLON;
  64029. (function (BABYLON) {
  64030. var BoneIKController = /** @class */ (function () {
  64031. function BoneIKController(mesh, bone, options) {
  64032. this.targetPosition = BABYLON.Vector3.Zero();
  64033. this.poleTargetPosition = BABYLON.Vector3.Zero();
  64034. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  64035. this.poleAngle = 0;
  64036. this.slerpAmount = 1;
  64037. this._bone1Quat = BABYLON.Quaternion.Identity();
  64038. this._bone1Mat = BABYLON.Matrix.Identity();
  64039. this._bone2Ang = Math.PI;
  64040. this._maxAngle = Math.PI;
  64041. this._rightHandedSystem = false;
  64042. this._bendAxis = BABYLON.Vector3.Right();
  64043. this._slerping = false;
  64044. this._adjustRoll = 0;
  64045. this._bone2 = bone;
  64046. this._bone1 = bone.getParent();
  64047. if (!this._bone1) {
  64048. return;
  64049. }
  64050. this.mesh = mesh;
  64051. var bonePos = bone.getPosition();
  64052. if (bone.getAbsoluteTransform().determinant() > 0) {
  64053. this._rightHandedSystem = true;
  64054. this._bendAxis.x = 0;
  64055. this._bendAxis.y = 0;
  64056. this._bendAxis.z = -1;
  64057. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  64058. this._adjustRoll = Math.PI * .5;
  64059. this._bendAxis.z = 1;
  64060. }
  64061. }
  64062. if (this._bone1.length) {
  64063. var boneScale1 = this._bone1.getScale();
  64064. var boneScale2 = this._bone2.getScale();
  64065. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  64066. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  64067. }
  64068. else if (this._bone1.children[0]) {
  64069. mesh.computeWorldMatrix(true);
  64070. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  64071. var pos2 = this._bone2.getAbsolutePosition(mesh);
  64072. var pos3 = this._bone1.getAbsolutePosition(mesh);
  64073. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  64074. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  64075. }
  64076. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  64077. this.maxAngle = Math.PI;
  64078. if (options) {
  64079. if (options.targetMesh) {
  64080. this.targetMesh = options.targetMesh;
  64081. this.targetMesh.computeWorldMatrix(true);
  64082. }
  64083. if (options.poleTargetMesh) {
  64084. this.poleTargetMesh = options.poleTargetMesh;
  64085. this.poleTargetMesh.computeWorldMatrix(true);
  64086. }
  64087. else if (options.poleTargetBone) {
  64088. this.poleTargetBone = options.poleTargetBone;
  64089. }
  64090. else if (this._bone1.getParent()) {
  64091. this.poleTargetBone = this._bone1.getParent();
  64092. }
  64093. if (options.poleTargetLocalOffset) {
  64094. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  64095. }
  64096. if (options.poleAngle) {
  64097. this.poleAngle = options.poleAngle;
  64098. }
  64099. if (options.bendAxis) {
  64100. this._bendAxis.copyFrom(options.bendAxis);
  64101. }
  64102. if (options.maxAngle) {
  64103. this.maxAngle = options.maxAngle;
  64104. }
  64105. if (options.slerpAmount) {
  64106. this.slerpAmount = options.slerpAmount;
  64107. }
  64108. }
  64109. }
  64110. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  64111. get: function () {
  64112. return this._maxAngle;
  64113. },
  64114. set: function (value) {
  64115. this._setMaxAngle(value);
  64116. },
  64117. enumerable: true,
  64118. configurable: true
  64119. });
  64120. BoneIKController.prototype._setMaxAngle = function (ang) {
  64121. if (ang < 0) {
  64122. ang = 0;
  64123. }
  64124. if (ang > Math.PI || ang == undefined) {
  64125. ang = Math.PI;
  64126. }
  64127. this._maxAngle = ang;
  64128. var a = this._bone1Length;
  64129. var b = this._bone2Length;
  64130. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  64131. };
  64132. BoneIKController.prototype.update = function () {
  64133. var bone1 = this._bone1;
  64134. if (!bone1) {
  64135. return;
  64136. }
  64137. var target = this.targetPosition;
  64138. var poleTarget = this.poleTargetPosition;
  64139. var mat1 = BoneIKController._tmpMats[0];
  64140. var mat2 = BoneIKController._tmpMats[1];
  64141. if (this.targetMesh) {
  64142. target.copyFrom(this.targetMesh.getAbsolutePosition());
  64143. }
  64144. if (this.poleTargetBone) {
  64145. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  64146. }
  64147. else if (this.poleTargetMesh) {
  64148. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  64149. }
  64150. var bonePos = BoneIKController._tmpVecs[0];
  64151. var zaxis = BoneIKController._tmpVecs[1];
  64152. var xaxis = BoneIKController._tmpVecs[2];
  64153. var yaxis = BoneIKController._tmpVecs[3];
  64154. var upAxis = BoneIKController._tmpVecs[4];
  64155. var _tmpQuat = BoneIKController._tmpQuat;
  64156. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  64157. poleTarget.subtractToRef(bonePos, upAxis);
  64158. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  64159. upAxis.y = 1;
  64160. }
  64161. else {
  64162. upAxis.normalize();
  64163. }
  64164. target.subtractToRef(bonePos, yaxis);
  64165. yaxis.normalize();
  64166. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  64167. zaxis.normalize();
  64168. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  64169. xaxis.normalize();
  64170. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  64171. var a = this._bone1Length;
  64172. var b = this._bone2Length;
  64173. var c = BABYLON.Vector3.Distance(bonePos, target);
  64174. if (this._maxReach > 0) {
  64175. c = Math.min(this._maxReach, c);
  64176. }
  64177. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  64178. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  64179. if (acosa > 1) {
  64180. acosa = 1;
  64181. }
  64182. if (acosb > 1) {
  64183. acosb = 1;
  64184. }
  64185. if (acosa < -1) {
  64186. acosa = -1;
  64187. }
  64188. if (acosb < -1) {
  64189. acosb = -1;
  64190. }
  64191. var angA = Math.acos(acosa);
  64192. var angB = Math.acos(acosb);
  64193. var angC = -angA - angB;
  64194. if (this._rightHandedSystem) {
  64195. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  64196. mat2.multiplyToRef(mat1, mat1);
  64197. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  64198. mat2.multiplyToRef(mat1, mat1);
  64199. }
  64200. else {
  64201. var _tmpVec = BoneIKController._tmpVecs[5];
  64202. _tmpVec.copyFrom(this._bendAxis);
  64203. _tmpVec.x *= -1;
  64204. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  64205. mat2.multiplyToRef(mat1, mat1);
  64206. }
  64207. if (this.poleAngle) {
  64208. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  64209. mat1.multiplyToRef(mat2, mat1);
  64210. }
  64211. if (this._bone1) {
  64212. if (this.slerpAmount < 1) {
  64213. if (!this._slerping) {
  64214. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  64215. }
  64216. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  64217. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  64218. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  64219. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  64220. this._slerping = true;
  64221. }
  64222. else {
  64223. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  64224. this._bone1Mat.copyFrom(mat1);
  64225. this._slerping = false;
  64226. }
  64227. }
  64228. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  64229. this._bone2Ang = angC;
  64230. };
  64231. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64232. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  64233. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64234. return BoneIKController;
  64235. }());
  64236. BABYLON.BoneIKController = BoneIKController;
  64237. })(BABYLON || (BABYLON = {}));
  64238. //# sourceMappingURL=babylon.boneIKController.js.map
  64239. var BABYLON;
  64240. (function (BABYLON) {
  64241. var BoneLookController = /** @class */ (function () {
  64242. /**
  64243. * Create a BoneLookController
  64244. * @param mesh the mesh that the bone belongs to
  64245. * @param bone the bone that will be looking to the target
  64246. * @param target the target Vector3 to look at
  64247. * @param settings optional settings:
  64248. * - maxYaw: the maximum angle the bone will yaw to
  64249. * - minYaw: the minimum angle the bone will yaw to
  64250. * - maxPitch: the maximum angle the bone will pitch to
  64251. * - minPitch: the minimum angle the bone will yaw to
  64252. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  64253. * - upAxis: the up axis of the coordinate system
  64254. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  64255. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  64256. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  64257. * - adjustYaw: used to make an adjustment to the yaw of the bone
  64258. * - adjustPitch: used to make an adjustment to the pitch of the bone
  64259. * - adjustRoll: used to make an adjustment to the roll of the bone
  64260. **/
  64261. function BoneLookController(mesh, bone, target, options) {
  64262. /**
  64263. * The up axis of the coordinate system that is used when the bone is rotated.
  64264. */
  64265. this.upAxis = BABYLON.Vector3.Up();
  64266. /**
  64267. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  64268. */
  64269. this.upAxisSpace = BABYLON.Space.LOCAL;
  64270. /**
  64271. * Used to make an adjustment to the yaw of the bone.
  64272. */
  64273. this.adjustYaw = 0;
  64274. /**
  64275. * Used to make an adjustment to the pitch of the bone.
  64276. */
  64277. this.adjustPitch = 0;
  64278. /**
  64279. * Used to make an adjustment to the roll of the bone.
  64280. */
  64281. this.adjustRoll = 0;
  64282. /**
  64283. * 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).
  64284. */
  64285. this.slerpAmount = 1;
  64286. this._boneQuat = BABYLON.Quaternion.Identity();
  64287. this._slerping = false;
  64288. this._firstFrameSkipped = false;
  64289. this._fowardAxis = BABYLON.Vector3.Forward();
  64290. this.mesh = mesh;
  64291. this.bone = bone;
  64292. this.target = target;
  64293. if (options) {
  64294. if (options.adjustYaw) {
  64295. this.adjustYaw = options.adjustYaw;
  64296. }
  64297. if (options.adjustPitch) {
  64298. this.adjustPitch = options.adjustPitch;
  64299. }
  64300. if (options.adjustRoll) {
  64301. this.adjustRoll = options.adjustRoll;
  64302. }
  64303. if (options.maxYaw != null) {
  64304. this.maxYaw = options.maxYaw;
  64305. }
  64306. else {
  64307. this.maxYaw = Math.PI;
  64308. }
  64309. if (options.minYaw != null) {
  64310. this.minYaw = options.minYaw;
  64311. }
  64312. else {
  64313. this.minYaw = -Math.PI;
  64314. }
  64315. if (options.maxPitch != null) {
  64316. this.maxPitch = options.maxPitch;
  64317. }
  64318. else {
  64319. this.maxPitch = Math.PI;
  64320. }
  64321. if (options.minPitch != null) {
  64322. this.minPitch = options.minPitch;
  64323. }
  64324. else {
  64325. this.minPitch = -Math.PI;
  64326. }
  64327. if (options.slerpAmount != null) {
  64328. this.slerpAmount = options.slerpAmount;
  64329. }
  64330. if (options.upAxis != null) {
  64331. this.upAxis = options.upAxis;
  64332. }
  64333. if (options.upAxisSpace != null) {
  64334. this.upAxisSpace = options.upAxisSpace;
  64335. }
  64336. if (options.yawAxis != null || options.pitchAxis != null) {
  64337. var newYawAxis = BABYLON.Axis.Y;
  64338. var newPitchAxis = BABYLON.Axis.X;
  64339. if (options.yawAxis != null) {
  64340. newYawAxis = options.yawAxis.clone();
  64341. newYawAxis.normalize();
  64342. }
  64343. if (options.pitchAxis != null) {
  64344. newPitchAxis = options.pitchAxis.clone();
  64345. newPitchAxis.normalize();
  64346. }
  64347. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  64348. this._transformYawPitch = BABYLON.Matrix.Identity();
  64349. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  64350. this._transformYawPitchInv = this._transformYawPitch.clone();
  64351. this._transformYawPitch.invert();
  64352. }
  64353. }
  64354. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  64355. this.upAxisSpace = BABYLON.Space.LOCAL;
  64356. }
  64357. }
  64358. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  64359. /**
  64360. * Get/set the minimum yaw angle that the bone can look to.
  64361. */
  64362. get: function () {
  64363. return this._minYaw;
  64364. },
  64365. set: function (value) {
  64366. this._minYaw = value;
  64367. this._minYawSin = Math.sin(value);
  64368. this._minYawCos = Math.cos(value);
  64369. if (this._maxYaw != null) {
  64370. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  64371. this._yawRange = this._maxYaw - this._minYaw;
  64372. }
  64373. },
  64374. enumerable: true,
  64375. configurable: true
  64376. });
  64377. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  64378. /**
  64379. * Get/set the maximum yaw angle that the bone can look to.
  64380. */
  64381. get: function () {
  64382. return this._maxYaw;
  64383. },
  64384. set: function (value) {
  64385. this._maxYaw = value;
  64386. this._maxYawSin = Math.sin(value);
  64387. this._maxYawCos = Math.cos(value);
  64388. if (this._minYaw != null) {
  64389. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  64390. this._yawRange = this._maxYaw - this._minYaw;
  64391. }
  64392. },
  64393. enumerable: true,
  64394. configurable: true
  64395. });
  64396. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  64397. /**
  64398. * Get/set the minimum pitch angle that the bone can look to.
  64399. */
  64400. get: function () {
  64401. return this._minPitch;
  64402. },
  64403. set: function (value) {
  64404. this._minPitch = value;
  64405. this._minPitchTan = Math.tan(value);
  64406. },
  64407. enumerable: true,
  64408. configurable: true
  64409. });
  64410. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  64411. /**
  64412. * Get/set the maximum pitch angle that the bone can look to.
  64413. */
  64414. get: function () {
  64415. return this._maxPitch;
  64416. },
  64417. set: function (value) {
  64418. this._maxPitch = value;
  64419. this._maxPitchTan = Math.tan(value);
  64420. },
  64421. enumerable: true,
  64422. configurable: true
  64423. });
  64424. /**
  64425. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  64426. */
  64427. BoneLookController.prototype.update = function () {
  64428. //skip the first frame when slerping so that the mesh rotation is correct
  64429. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  64430. this._firstFrameSkipped = true;
  64431. return;
  64432. }
  64433. var bone = this.bone;
  64434. var bonePos = BoneLookController._tmpVecs[0];
  64435. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  64436. var target = this.target;
  64437. var _tmpMat1 = BoneLookController._tmpMats[0];
  64438. var _tmpMat2 = BoneLookController._tmpMats[1];
  64439. var mesh = this.mesh;
  64440. var parentBone = bone.getParent();
  64441. var upAxis = BoneLookController._tmpVecs[1];
  64442. upAxis.copyFrom(this.upAxis);
  64443. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  64444. if (this._transformYawPitch) {
  64445. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  64446. }
  64447. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  64448. }
  64449. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  64450. mesh.getDirectionToRef(upAxis, upAxis);
  64451. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  64452. upAxis.normalize();
  64453. }
  64454. }
  64455. var checkYaw = false;
  64456. var checkPitch = false;
  64457. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  64458. checkYaw = true;
  64459. }
  64460. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  64461. checkPitch = true;
  64462. }
  64463. if (checkYaw || checkPitch) {
  64464. var spaceMat = BoneLookController._tmpMats[2];
  64465. var spaceMatInv = BoneLookController._tmpMats[3];
  64466. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  64467. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  64468. }
  64469. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  64470. spaceMat.copyFrom(mesh.getWorldMatrix());
  64471. }
  64472. else {
  64473. var forwardAxis = BoneLookController._tmpVecs[2];
  64474. forwardAxis.copyFrom(this._fowardAxis);
  64475. if (this._transformYawPitch) {
  64476. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  64477. }
  64478. if (parentBone) {
  64479. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  64480. }
  64481. else {
  64482. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  64483. }
  64484. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  64485. rightAxis.normalize();
  64486. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  64487. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  64488. }
  64489. spaceMat.invertToRef(spaceMatInv);
  64490. var xzlen = null;
  64491. if (checkPitch) {
  64492. var localTarget = BoneLookController._tmpVecs[3];
  64493. target.subtractToRef(bonePos, localTarget);
  64494. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  64495. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64496. var pitch = Math.atan2(localTarget.y, xzlen);
  64497. var newPitch = pitch;
  64498. if (pitch > this._maxPitch) {
  64499. localTarget.y = this._maxPitchTan * xzlen;
  64500. newPitch = this._maxPitch;
  64501. }
  64502. else if (pitch < this._minPitch) {
  64503. localTarget.y = this._minPitchTan * xzlen;
  64504. newPitch = this._minPitch;
  64505. }
  64506. if (pitch != newPitch) {
  64507. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  64508. localTarget.addInPlace(bonePos);
  64509. target = localTarget;
  64510. }
  64511. }
  64512. if (checkYaw) {
  64513. var localTarget = BoneLookController._tmpVecs[4];
  64514. target.subtractToRef(bonePos, localTarget);
  64515. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  64516. var yaw = Math.atan2(localTarget.x, localTarget.z);
  64517. var newYaw = yaw;
  64518. if (yaw > this._maxYaw || yaw < this._minYaw) {
  64519. if (xzlen == null) {
  64520. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64521. }
  64522. if (this._yawRange > Math.PI) {
  64523. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  64524. localTarget.z = this._maxYawCos * xzlen;
  64525. localTarget.x = this._maxYawSin * xzlen;
  64526. newYaw = this._maxYaw;
  64527. }
  64528. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  64529. localTarget.z = this._minYawCos * xzlen;
  64530. localTarget.x = this._minYawSin * xzlen;
  64531. newYaw = this._minYaw;
  64532. }
  64533. }
  64534. else {
  64535. if (yaw > this._maxYaw) {
  64536. localTarget.z = this._maxYawCos * xzlen;
  64537. localTarget.x = this._maxYawSin * xzlen;
  64538. newYaw = this._maxYaw;
  64539. }
  64540. else if (yaw < this._minYaw) {
  64541. localTarget.z = this._minYawCos * xzlen;
  64542. localTarget.x = this._minYawSin * xzlen;
  64543. newYaw = this._minYaw;
  64544. }
  64545. }
  64546. }
  64547. if (this._slerping && this._yawRange > Math.PI) {
  64548. //are we going to be crossing into the min/max region?
  64549. var boneFwd = BoneLookController._tmpVecs[8];
  64550. boneFwd.copyFrom(BABYLON.Axis.Z);
  64551. if (this._transformYawPitch) {
  64552. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  64553. }
  64554. var boneRotMat = BoneLookController._tmpMats[4];
  64555. this._boneQuat.toRotationMatrix(boneRotMat);
  64556. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  64557. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  64558. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  64559. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  64560. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  64561. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  64562. if (angBtwTar > angBtwMidYaw) {
  64563. if (xzlen == null) {
  64564. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64565. }
  64566. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  64567. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  64568. if (angBtwMin < angBtwMax) {
  64569. newYaw = boneYaw + Math.PI * .75;
  64570. localTarget.z = Math.cos(newYaw) * xzlen;
  64571. localTarget.x = Math.sin(newYaw) * xzlen;
  64572. }
  64573. else {
  64574. newYaw = boneYaw - Math.PI * .75;
  64575. localTarget.z = Math.cos(newYaw) * xzlen;
  64576. localTarget.x = Math.sin(newYaw) * xzlen;
  64577. }
  64578. }
  64579. }
  64580. if (yaw != newYaw) {
  64581. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  64582. localTarget.addInPlace(bonePos);
  64583. target = localTarget;
  64584. }
  64585. }
  64586. }
  64587. var zaxis = BoneLookController._tmpVecs[5];
  64588. var xaxis = BoneLookController._tmpVecs[6];
  64589. var yaxis = BoneLookController._tmpVecs[7];
  64590. var _tmpQuat = BoneLookController._tmpQuat;
  64591. target.subtractToRef(bonePos, zaxis);
  64592. zaxis.normalize();
  64593. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  64594. xaxis.normalize();
  64595. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  64596. yaxis.normalize();
  64597. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  64598. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  64599. return;
  64600. }
  64601. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  64602. return;
  64603. }
  64604. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  64605. return;
  64606. }
  64607. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  64608. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  64609. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  64610. }
  64611. if (this.slerpAmount < 1) {
  64612. if (!this._slerping) {
  64613. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  64614. }
  64615. if (this._transformYawPitch) {
  64616. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  64617. }
  64618. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  64619. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  64620. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  64621. this._slerping = true;
  64622. }
  64623. else {
  64624. if (this._transformYawPitch) {
  64625. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  64626. }
  64627. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  64628. this._slerping = false;
  64629. }
  64630. };
  64631. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  64632. var angDiff = ang2 - ang1;
  64633. angDiff %= Math.PI * 2;
  64634. if (angDiff > Math.PI) {
  64635. angDiff -= Math.PI * 2;
  64636. }
  64637. else if (angDiff < -Math.PI) {
  64638. angDiff += Math.PI * 2;
  64639. }
  64640. return angDiff;
  64641. };
  64642. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  64643. ang1 %= (2 * Math.PI);
  64644. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  64645. ang2 %= (2 * Math.PI);
  64646. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  64647. var ab = 0;
  64648. if (ang1 < ang2) {
  64649. ab = ang2 - ang1;
  64650. }
  64651. else {
  64652. ab = ang1 - ang2;
  64653. }
  64654. if (ab > Math.PI) {
  64655. ab = Math.PI * 2 - ab;
  64656. }
  64657. return ab;
  64658. };
  64659. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  64660. ang %= (2 * Math.PI);
  64661. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  64662. ang1 %= (2 * Math.PI);
  64663. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  64664. ang2 %= (2 * Math.PI);
  64665. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  64666. if (ang1 < ang2) {
  64667. if (ang > ang1 && ang < ang2) {
  64668. return true;
  64669. }
  64670. }
  64671. else {
  64672. if (ang > ang2 && ang < ang1) {
  64673. return true;
  64674. }
  64675. }
  64676. return false;
  64677. };
  64678. 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()];
  64679. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  64680. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64681. return BoneLookController;
  64682. }());
  64683. BABYLON.BoneLookController = BoneLookController;
  64684. })(BABYLON || (BABYLON = {}));
  64685. //# sourceMappingURL=babylon.boneLookController.js.map
  64686. var BABYLON;
  64687. (function (BABYLON) {
  64688. var Skeleton = /** @class */ (function () {
  64689. function Skeleton(name, id, scene) {
  64690. this.name = name;
  64691. this.id = id;
  64692. this.bones = new Array();
  64693. this.needInitialSkinMatrix = false;
  64694. this._isDirty = true;
  64695. this._meshesWithPoseMatrix = new Array();
  64696. this._identity = BABYLON.Matrix.Identity();
  64697. this._ranges = {};
  64698. this._lastAbsoluteTransformsUpdateId = -1;
  64699. // Events
  64700. /**
  64701. * An event triggered before computing the skeleton's matrices
  64702. * @type {BABYLON.Observable}
  64703. */
  64704. this.onBeforeComputeObservable = new BABYLON.Observable();
  64705. this.bones = [];
  64706. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64707. scene.skeletons.push(this);
  64708. //make sure it will recalculate the matrix next time prepare is called.
  64709. this._isDirty = true;
  64710. }
  64711. // Members
  64712. Skeleton.prototype.getTransformMatrices = function (mesh) {
  64713. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  64714. return mesh._bonesTransformMatrices;
  64715. }
  64716. if (!this._transformMatrices) {
  64717. this.prepare();
  64718. }
  64719. return this._transformMatrices;
  64720. };
  64721. Skeleton.prototype.getScene = function () {
  64722. return this._scene;
  64723. };
  64724. // Methods
  64725. /**
  64726. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  64727. */
  64728. Skeleton.prototype.toString = function (fullDetails) {
  64729. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  64730. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  64731. if (fullDetails) {
  64732. ret += ", Ranges: {";
  64733. var first = true;
  64734. for (var name_1 in this._ranges) {
  64735. if (first) {
  64736. ret += ", ";
  64737. first = false;
  64738. }
  64739. ret += name_1;
  64740. }
  64741. ret += "}";
  64742. }
  64743. return ret;
  64744. };
  64745. /**
  64746. * Get bone's index searching by name
  64747. * @param {string} name is bone's name to search for
  64748. * @return {number} Indice of the bone. Returns -1 if not found
  64749. */
  64750. Skeleton.prototype.getBoneIndexByName = function (name) {
  64751. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  64752. if (this.bones[boneIndex].name === name) {
  64753. return boneIndex;
  64754. }
  64755. }
  64756. return -1;
  64757. };
  64758. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  64759. // check name not already in use
  64760. if (!this._ranges[name]) {
  64761. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  64762. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64763. if (this.bones[i].animations[0]) {
  64764. this.bones[i].animations[0].createRange(name, from, to);
  64765. }
  64766. }
  64767. }
  64768. };
  64769. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  64770. if (deleteFrames === void 0) { deleteFrames = true; }
  64771. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64772. if (this.bones[i].animations[0]) {
  64773. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  64774. }
  64775. }
  64776. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  64777. };
  64778. Skeleton.prototype.getAnimationRange = function (name) {
  64779. return this._ranges[name];
  64780. };
  64781. /**
  64782. * Returns as an Array, all AnimationRanges defined on this skeleton
  64783. */
  64784. Skeleton.prototype.getAnimationRanges = function () {
  64785. var animationRanges = [];
  64786. var name;
  64787. var i = 0;
  64788. for (name in this._ranges) {
  64789. animationRanges[i] = this._ranges[name];
  64790. i++;
  64791. }
  64792. return animationRanges;
  64793. };
  64794. /**
  64795. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  64796. */
  64797. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  64798. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  64799. if (this._ranges[name] || !source.getAnimationRange(name)) {
  64800. return false;
  64801. }
  64802. var ret = true;
  64803. var frameOffset = this._getHighestAnimationFrame() + 1;
  64804. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  64805. var boneDict = {};
  64806. var sourceBones = source.bones;
  64807. var nBones;
  64808. var i;
  64809. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  64810. boneDict[sourceBones[i].name] = sourceBones[i];
  64811. }
  64812. if (this.bones.length !== sourceBones.length) {
  64813. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  64814. ret = false;
  64815. }
  64816. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  64817. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  64818. var boneName = this.bones[i].name;
  64819. var sourceBone = boneDict[boneName];
  64820. if (sourceBone) {
  64821. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  64822. }
  64823. else {
  64824. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  64825. ret = false;
  64826. }
  64827. }
  64828. // do not call createAnimationRange(), since it also is done to bones, which was already done
  64829. var range = source.getAnimationRange(name);
  64830. if (range) {
  64831. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  64832. }
  64833. return ret;
  64834. };
  64835. Skeleton.prototype.returnToRest = function () {
  64836. for (var index = 0; index < this.bones.length; index++) {
  64837. this.bones[index].returnToRest();
  64838. }
  64839. };
  64840. Skeleton.prototype._getHighestAnimationFrame = function () {
  64841. var ret = 0;
  64842. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64843. if (this.bones[i].animations[0]) {
  64844. var highest = this.bones[i].animations[0].getHighestFrame();
  64845. if (ret < highest) {
  64846. ret = highest;
  64847. }
  64848. }
  64849. }
  64850. return ret;
  64851. };
  64852. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  64853. var range = this.getAnimationRange(name);
  64854. if (!range) {
  64855. return null;
  64856. }
  64857. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  64858. };
  64859. Skeleton.prototype._markAsDirty = function () {
  64860. this._isDirty = true;
  64861. };
  64862. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  64863. this._meshesWithPoseMatrix.push(mesh);
  64864. };
  64865. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  64866. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  64867. if (index > -1) {
  64868. this._meshesWithPoseMatrix.splice(index, 1);
  64869. }
  64870. };
  64871. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  64872. this.onBeforeComputeObservable.notifyObservers(this);
  64873. for (var index = 0; index < this.bones.length; index++) {
  64874. var bone = this.bones[index];
  64875. var parentBone = bone.getParent();
  64876. if (parentBone) {
  64877. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  64878. }
  64879. else {
  64880. if (initialSkinMatrix) {
  64881. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  64882. }
  64883. else {
  64884. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  64885. }
  64886. }
  64887. if (bone._index !== -1) {
  64888. var mappedIndex = bone._index === null ? index : bone._index;
  64889. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  64890. }
  64891. }
  64892. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  64893. };
  64894. Skeleton.prototype.prepare = function () {
  64895. if (!this._isDirty) {
  64896. return;
  64897. }
  64898. if (this.needInitialSkinMatrix) {
  64899. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  64900. var mesh = this._meshesWithPoseMatrix[index];
  64901. var poseMatrix = mesh.getPoseMatrix();
  64902. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  64903. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  64904. }
  64905. if (this._synchronizedWithMesh !== mesh) {
  64906. this._synchronizedWithMesh = mesh;
  64907. // Prepare bones
  64908. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  64909. var bone = this.bones[boneIndex];
  64910. if (!bone.getParent()) {
  64911. var matrix = bone.getBaseMatrix();
  64912. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  64913. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  64914. }
  64915. }
  64916. }
  64917. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  64918. }
  64919. }
  64920. else {
  64921. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  64922. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  64923. }
  64924. this._computeTransformMatrices(this._transformMatrices, null);
  64925. }
  64926. this._isDirty = false;
  64927. this._scene._activeBones.addCount(this.bones.length, false);
  64928. };
  64929. Skeleton.prototype.getAnimatables = function () {
  64930. if (!this._animatables || this._animatables.length !== this.bones.length) {
  64931. this._animatables = [];
  64932. for (var index = 0; index < this.bones.length; index++) {
  64933. this._animatables.push(this.bones[index]);
  64934. }
  64935. }
  64936. return this._animatables;
  64937. };
  64938. Skeleton.prototype.clone = function (name, id) {
  64939. var result = new Skeleton(name, id || name, this._scene);
  64940. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  64941. for (var index = 0; index < this.bones.length; index++) {
  64942. var source = this.bones[index];
  64943. var parentBone = null;
  64944. var parent_1 = source.getParent();
  64945. if (parent_1) {
  64946. var parentIndex = this.bones.indexOf(parent_1);
  64947. parentBone = result.bones[parentIndex];
  64948. }
  64949. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  64950. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  64951. }
  64952. if (this._ranges) {
  64953. result._ranges = {};
  64954. for (var rangeName in this._ranges) {
  64955. var range = this._ranges[rangeName];
  64956. if (range) {
  64957. result._ranges[rangeName] = range.clone();
  64958. }
  64959. }
  64960. }
  64961. this._isDirty = true;
  64962. return result;
  64963. };
  64964. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  64965. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  64966. this.bones.forEach(function (bone) {
  64967. bone.animations.forEach(function (animation) {
  64968. animation.enableBlending = true;
  64969. animation.blendingSpeed = blendingSpeed;
  64970. });
  64971. });
  64972. };
  64973. Skeleton.prototype.dispose = function () {
  64974. this._meshesWithPoseMatrix = [];
  64975. // Animations
  64976. this.getScene().stopAnimation(this);
  64977. // Remove from scene
  64978. this.getScene().removeSkeleton(this);
  64979. };
  64980. Skeleton.prototype.serialize = function () {
  64981. var serializationObject = {};
  64982. serializationObject.name = this.name;
  64983. serializationObject.id = this.id;
  64984. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  64985. serializationObject.bones = [];
  64986. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  64987. for (var index = 0; index < this.bones.length; index++) {
  64988. var bone = this.bones[index];
  64989. var parent_2 = bone.getParent();
  64990. var serializedBone = {
  64991. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  64992. name: bone.name,
  64993. matrix: bone.getBaseMatrix().toArray(),
  64994. rest: bone.getRestPose().toArray()
  64995. };
  64996. serializationObject.bones.push(serializedBone);
  64997. if (bone.length) {
  64998. serializedBone.length = bone.length;
  64999. }
  65000. if (bone.animations && bone.animations.length > 0) {
  65001. serializedBone.animation = bone.animations[0].serialize();
  65002. }
  65003. serializationObject.ranges = [];
  65004. for (var name in this._ranges) {
  65005. var source = this._ranges[name];
  65006. if (!source) {
  65007. continue;
  65008. }
  65009. var range = {};
  65010. range.name = name;
  65011. range.from = source.from;
  65012. range.to = source.to;
  65013. serializationObject.ranges.push(range);
  65014. }
  65015. }
  65016. return serializationObject;
  65017. };
  65018. Skeleton.Parse = function (parsedSkeleton, scene) {
  65019. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  65020. if (parsedSkeleton.dimensionsAtRest) {
  65021. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  65022. }
  65023. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  65024. var index;
  65025. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  65026. var parsedBone = parsedSkeleton.bones[index];
  65027. var parentBone = null;
  65028. if (parsedBone.parentBoneIndex > -1) {
  65029. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  65030. }
  65031. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  65032. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  65033. if (parsedBone.length) {
  65034. bone.length = parsedBone.length;
  65035. }
  65036. if (parsedBone.animation) {
  65037. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  65038. }
  65039. }
  65040. // placed after bones, so createAnimationRange can cascade down
  65041. if (parsedSkeleton.ranges) {
  65042. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  65043. var data = parsedSkeleton.ranges[index];
  65044. skeleton.createAnimationRange(data.name, data.from, data.to);
  65045. }
  65046. }
  65047. return skeleton;
  65048. };
  65049. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  65050. if (forceUpdate === void 0) { forceUpdate = false; }
  65051. var renderId = this._scene.getRenderId();
  65052. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  65053. this.bones[0].computeAbsoluteTransforms();
  65054. this._lastAbsoluteTransformsUpdateId = renderId;
  65055. }
  65056. };
  65057. Skeleton.prototype.getPoseMatrix = function () {
  65058. var poseMatrix = null;
  65059. if (this._meshesWithPoseMatrix.length > 0) {
  65060. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  65061. }
  65062. return poseMatrix;
  65063. };
  65064. Skeleton.prototype.sortBones = function () {
  65065. var bones = new Array();
  65066. var visited = new Array(this.bones.length);
  65067. for (var index = 0; index < this.bones.length; index++) {
  65068. this._sortBones(index, bones, visited);
  65069. }
  65070. this.bones = bones;
  65071. };
  65072. Skeleton.prototype._sortBones = function (index, bones, visited) {
  65073. if (visited[index]) {
  65074. return;
  65075. }
  65076. visited[index] = true;
  65077. var bone = this.bones[index];
  65078. if (bone._index === undefined) {
  65079. bone._index = index;
  65080. }
  65081. var parentBone = bone.getParent();
  65082. if (parentBone) {
  65083. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  65084. }
  65085. bones.push(bone);
  65086. };
  65087. return Skeleton;
  65088. }());
  65089. BABYLON.Skeleton = Skeleton;
  65090. })(BABYLON || (BABYLON = {}));
  65091. //# sourceMappingURL=babylon.skeleton.js.map
  65092. var BABYLON;
  65093. (function (BABYLON) {
  65094. var SphericalPolynomial = /** @class */ (function () {
  65095. function SphericalPolynomial() {
  65096. this.x = BABYLON.Vector3.Zero();
  65097. this.y = BABYLON.Vector3.Zero();
  65098. this.z = BABYLON.Vector3.Zero();
  65099. this.xx = BABYLON.Vector3.Zero();
  65100. this.yy = BABYLON.Vector3.Zero();
  65101. this.zz = BABYLON.Vector3.Zero();
  65102. this.xy = BABYLON.Vector3.Zero();
  65103. this.yz = BABYLON.Vector3.Zero();
  65104. this.zx = BABYLON.Vector3.Zero();
  65105. }
  65106. SphericalPolynomial.prototype.addAmbient = function (color) {
  65107. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  65108. this.xx = this.xx.add(colorVector);
  65109. this.yy = this.yy.add(colorVector);
  65110. this.zz = this.zz.add(colorVector);
  65111. };
  65112. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  65113. var result = new SphericalPolynomial();
  65114. result.x = harmonics.L11.scale(1.02333);
  65115. result.y = harmonics.L1_1.scale(1.02333);
  65116. result.z = harmonics.L10.scale(1.02333);
  65117. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  65118. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  65119. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  65120. result.yz = harmonics.L2_1.scale(0.858086);
  65121. result.zx = harmonics.L21.scale(0.858086);
  65122. result.xy = harmonics.L2_2.scale(0.858086);
  65123. result.scale(1.0 / Math.PI);
  65124. return result;
  65125. };
  65126. SphericalPolynomial.prototype.scale = function (scale) {
  65127. this.x = this.x.scale(scale);
  65128. this.y = this.y.scale(scale);
  65129. this.z = this.z.scale(scale);
  65130. this.xx = this.xx.scale(scale);
  65131. this.yy = this.yy.scale(scale);
  65132. this.zz = this.zz.scale(scale);
  65133. this.yz = this.yz.scale(scale);
  65134. this.zx = this.zx.scale(scale);
  65135. this.xy = this.xy.scale(scale);
  65136. };
  65137. return SphericalPolynomial;
  65138. }());
  65139. BABYLON.SphericalPolynomial = SphericalPolynomial;
  65140. var SphericalHarmonics = /** @class */ (function () {
  65141. function SphericalHarmonics() {
  65142. this.L00 = BABYLON.Vector3.Zero();
  65143. this.L1_1 = BABYLON.Vector3.Zero();
  65144. this.L10 = BABYLON.Vector3.Zero();
  65145. this.L11 = BABYLON.Vector3.Zero();
  65146. this.L2_2 = BABYLON.Vector3.Zero();
  65147. this.L2_1 = BABYLON.Vector3.Zero();
  65148. this.L20 = BABYLON.Vector3.Zero();
  65149. this.L21 = BABYLON.Vector3.Zero();
  65150. this.L22 = BABYLON.Vector3.Zero();
  65151. }
  65152. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  65153. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  65154. var c = colorVector.scale(deltaSolidAngle);
  65155. this.L00 = this.L00.add(c.scale(0.282095));
  65156. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  65157. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  65158. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  65159. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  65160. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  65161. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  65162. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  65163. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  65164. };
  65165. SphericalHarmonics.prototype.scale = function (scale) {
  65166. this.L00 = this.L00.scale(scale);
  65167. this.L1_1 = this.L1_1.scale(scale);
  65168. this.L10 = this.L10.scale(scale);
  65169. this.L11 = this.L11.scale(scale);
  65170. this.L2_2 = this.L2_2.scale(scale);
  65171. this.L2_1 = this.L2_1.scale(scale);
  65172. this.L20 = this.L20.scale(scale);
  65173. this.L21 = this.L21.scale(scale);
  65174. this.L22 = this.L22.scale(scale);
  65175. };
  65176. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  65177. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  65178. //
  65179. // E_lm = A_l * L_lm
  65180. //
  65181. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  65182. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  65183. // the scaling factors are given in equation 9.
  65184. // Constant (Band 0)
  65185. this.L00 = this.L00.scale(3.141593);
  65186. // Linear (Band 1)
  65187. this.L1_1 = this.L1_1.scale(2.094395);
  65188. this.L10 = this.L10.scale(2.094395);
  65189. this.L11 = this.L11.scale(2.094395);
  65190. // Quadratic (Band 2)
  65191. this.L2_2 = this.L2_2.scale(0.785398);
  65192. this.L2_1 = this.L2_1.scale(0.785398);
  65193. this.L20 = this.L20.scale(0.785398);
  65194. this.L21 = this.L21.scale(0.785398);
  65195. this.L22 = this.L22.scale(0.785398);
  65196. };
  65197. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  65198. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  65199. // L = (1/pi) * E * rho
  65200. //
  65201. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  65202. this.scale(1.0 / Math.PI);
  65203. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  65204. // (The pixel shader must apply albedo after texture fetches, etc).
  65205. };
  65206. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  65207. var result = new SphericalHarmonics();
  65208. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  65209. result.L1_1 = polynomial.y.scale(0.977204);
  65210. result.L10 = polynomial.z.scale(0.977204);
  65211. result.L11 = polynomial.x.scale(0.977204);
  65212. result.L2_2 = polynomial.xy.scale(1.16538);
  65213. result.L2_1 = polynomial.yz.scale(1.16538);
  65214. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  65215. result.L21 = polynomial.zx.scale(1.16538);
  65216. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  65217. result.scale(Math.PI);
  65218. return result;
  65219. };
  65220. return SphericalHarmonics;
  65221. }());
  65222. BABYLON.SphericalHarmonics = SphericalHarmonics;
  65223. })(BABYLON || (BABYLON = {}));
  65224. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  65225. var BABYLON;
  65226. (function (BABYLON) {
  65227. var FileFaceOrientation = /** @class */ (function () {
  65228. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  65229. this.name = name;
  65230. this.worldAxisForNormal = worldAxisForNormal;
  65231. this.worldAxisForFileX = worldAxisForFileX;
  65232. this.worldAxisForFileY = worldAxisForFileY;
  65233. }
  65234. return FileFaceOrientation;
  65235. }());
  65236. ;
  65237. /**
  65238. * Helper class dealing with the extraction of spherical polynomial dataArray
  65239. * from a cube map.
  65240. */
  65241. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  65242. function CubeMapToSphericalPolynomialTools() {
  65243. }
  65244. /**
  65245. * Converts a texture to the according Spherical Polynomial data.
  65246. * This extracts the first 3 orders only as they are the only one used in the lighting.
  65247. *
  65248. * @param texture The texture to extract the information from.
  65249. * @return The Spherical Polynomial data.
  65250. */
  65251. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  65252. if (!texture.isCube) {
  65253. // Only supports cube Textures currently.
  65254. return null;
  65255. }
  65256. var size = texture.getSize().width;
  65257. var right = texture.readPixels(0);
  65258. var left = texture.readPixels(1);
  65259. var up;
  65260. var down;
  65261. if (texture.isRenderTarget) {
  65262. up = texture.readPixels(3);
  65263. down = texture.readPixels(2);
  65264. }
  65265. else {
  65266. up = texture.readPixels(2);
  65267. down = texture.readPixels(3);
  65268. }
  65269. var front = texture.readPixels(4);
  65270. var back = texture.readPixels(5);
  65271. var gammaSpace = texture.gammaSpace;
  65272. // Always read as RGBA.
  65273. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  65274. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65275. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65276. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65277. }
  65278. var cubeInfo = {
  65279. size: size,
  65280. right: right,
  65281. left: left,
  65282. up: up,
  65283. down: down,
  65284. front: front,
  65285. back: back,
  65286. format: format,
  65287. type: type,
  65288. gammaSpace: gammaSpace,
  65289. };
  65290. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  65291. };
  65292. /**
  65293. * Converts a cubemap to the according Spherical Polynomial data.
  65294. * This extracts the first 3 orders only as they are the only one used in the lighting.
  65295. *
  65296. * @param cubeInfo The Cube map to extract the information from.
  65297. * @return The Spherical Polynomial data.
  65298. */
  65299. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  65300. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  65301. var totalSolidAngle = 0.0;
  65302. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  65303. var du = 2.0 / cubeInfo.size;
  65304. var dv = du;
  65305. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  65306. var minUV = du * 0.5 - 1.0;
  65307. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65308. var fileFace = this.FileFaces[faceIndex];
  65309. var dataArray = cubeInfo[fileFace.name];
  65310. var v = minUV;
  65311. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  65312. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  65313. // Because SP is still linear, so summation is fine in that basis.
  65314. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  65315. for (var y = 0; y < cubeInfo.size; y++) {
  65316. var u = minUV;
  65317. for (var x = 0; x < cubeInfo.size; x++) {
  65318. // World direction (not normalised)
  65319. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  65320. worldDirection.normalize();
  65321. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  65322. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  65323. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  65324. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  65325. // Handle Integer types.
  65326. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65327. r /= 255;
  65328. g /= 255;
  65329. b /= 255;
  65330. }
  65331. // Handle Gamma space textures.
  65332. if (cubeInfo.gammaSpace) {
  65333. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  65334. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  65335. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  65336. }
  65337. var color = new BABYLON.Color3(r, g, b);
  65338. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  65339. totalSolidAngle += deltaSolidAngle;
  65340. u += du;
  65341. }
  65342. v += dv;
  65343. }
  65344. }
  65345. // Solid angle for entire sphere is 4*pi
  65346. var sphereSolidAngle = 4.0 * Math.PI;
  65347. // Adjust the solid angle to allow for how many faces we processed.
  65348. var facesProcessed = 6.0;
  65349. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  65350. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  65351. // This is needed because the numerical integration over the cube uses a
  65352. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  65353. // and also to compensate for accumulative error due to float precision in the summation.
  65354. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  65355. sphericalHarmonics.scale(correctionFactor);
  65356. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  65357. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  65358. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  65359. };
  65360. CubeMapToSphericalPolynomialTools.FileFaces = [
  65361. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  65362. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  65363. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  65364. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  65365. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  65366. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  65367. ];
  65368. return CubeMapToSphericalPolynomialTools;
  65369. }());
  65370. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  65371. })(BABYLON || (BABYLON = {}));
  65372. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  65373. var BABYLON;
  65374. (function (BABYLON) {
  65375. /**
  65376. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  65377. */
  65378. var PanoramaToCubeMapTools = /** @class */ (function () {
  65379. function PanoramaToCubeMapTools() {
  65380. }
  65381. /**
  65382. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  65383. *
  65384. * @param float32Array The source data.
  65385. * @param inputWidth The width of the input panorama.
  65386. * @param inputhHeight The height of the input panorama.
  65387. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  65388. * @return The cubemap data
  65389. */
  65390. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  65391. if (!float32Array) {
  65392. throw "ConvertPanoramaToCubemap: input cannot be null";
  65393. }
  65394. if (float32Array.length != inputWidth * inputHeight * 3) {
  65395. throw "ConvertPanoramaToCubemap: input size is wrong";
  65396. }
  65397. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  65398. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  65399. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  65400. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  65401. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  65402. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  65403. return {
  65404. front: textureFront,
  65405. back: textureBack,
  65406. left: textureLeft,
  65407. right: textureRight,
  65408. up: textureUp,
  65409. down: textureDown,
  65410. size: size,
  65411. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  65412. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  65413. gammaSpace: false,
  65414. };
  65415. };
  65416. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  65417. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  65418. var textureArray = new Float32Array(buffer);
  65419. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  65420. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  65421. var dy = 1 / texSize;
  65422. var fy = 0;
  65423. for (var y = 0; y < texSize; y++) {
  65424. var xv1 = faceData[0];
  65425. var xv2 = faceData[2];
  65426. for (var x = 0; x < texSize; x++) {
  65427. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  65428. v.normalize();
  65429. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  65430. // 3 channels per pixels
  65431. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  65432. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  65433. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  65434. xv1 = xv1.add(rotDX1);
  65435. xv2 = xv2.add(rotDX2);
  65436. }
  65437. fy += dy;
  65438. }
  65439. return textureArray;
  65440. };
  65441. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  65442. var theta = Math.atan2(vDir.z, vDir.x);
  65443. var phi = Math.acos(vDir.y);
  65444. while (theta < -Math.PI)
  65445. theta += 2 * Math.PI;
  65446. while (theta > Math.PI)
  65447. theta -= 2 * Math.PI;
  65448. var dx = theta / Math.PI;
  65449. var dy = phi / Math.PI;
  65450. // recenter.
  65451. dx = dx * 0.5 + 0.5;
  65452. var px = Math.round(dx * inputWidth);
  65453. if (px < 0)
  65454. px = 0;
  65455. else if (px >= inputWidth)
  65456. px = inputWidth - 1;
  65457. var py = Math.round(dy * inputHeight);
  65458. if (py < 0)
  65459. py = 0;
  65460. else if (py >= inputHeight)
  65461. py = inputHeight - 1;
  65462. var inputY = (inputHeight - py - 1);
  65463. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  65464. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  65465. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  65466. return {
  65467. r: r,
  65468. g: g,
  65469. b: b
  65470. };
  65471. };
  65472. PanoramaToCubeMapTools.FACE_FRONT = [
  65473. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65474. new BABYLON.Vector3(1.0, -1.0, -1.0),
  65475. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  65476. new BABYLON.Vector3(1.0, 1.0, -1.0)
  65477. ];
  65478. PanoramaToCubeMapTools.FACE_BACK = [
  65479. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65480. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65481. new BABYLON.Vector3(1.0, 1.0, 1.0),
  65482. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  65483. ];
  65484. PanoramaToCubeMapTools.FACE_RIGHT = [
  65485. new BABYLON.Vector3(1.0, -1.0, -1.0),
  65486. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65487. new BABYLON.Vector3(1.0, 1.0, -1.0),
  65488. new BABYLON.Vector3(1.0, 1.0, 1.0)
  65489. ];
  65490. PanoramaToCubeMapTools.FACE_LEFT = [
  65491. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65492. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65493. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  65494. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  65495. ];
  65496. PanoramaToCubeMapTools.FACE_DOWN = [
  65497. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  65498. new BABYLON.Vector3(1.0, 1.0, -1.0),
  65499. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  65500. new BABYLON.Vector3(1.0, 1.0, 1.0)
  65501. ];
  65502. PanoramaToCubeMapTools.FACE_UP = [
  65503. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65504. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65505. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65506. new BABYLON.Vector3(1.0, -1.0, -1.0)
  65507. ];
  65508. return PanoramaToCubeMapTools;
  65509. }());
  65510. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  65511. })(BABYLON || (BABYLON = {}));
  65512. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  65513. var BABYLON;
  65514. (function (BABYLON) {
  65515. ;
  65516. /**
  65517. * This groups tools to convert HDR texture to native colors array.
  65518. */
  65519. var HDRTools = /** @class */ (function () {
  65520. function HDRTools() {
  65521. }
  65522. HDRTools.Ldexp = function (mantissa, exponent) {
  65523. if (exponent > 1023) {
  65524. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  65525. }
  65526. if (exponent < -1074) {
  65527. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  65528. }
  65529. return mantissa * Math.pow(2, exponent);
  65530. };
  65531. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  65532. if (exponent > 0) {
  65533. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  65534. float32array[index + 0] = red * exponent;
  65535. float32array[index + 1] = green * exponent;
  65536. float32array[index + 2] = blue * exponent;
  65537. }
  65538. else {
  65539. float32array[index + 0] = 0;
  65540. float32array[index + 1] = 0;
  65541. float32array[index + 2] = 0;
  65542. }
  65543. };
  65544. HDRTools.readStringLine = function (uint8array, startIndex) {
  65545. var line = "";
  65546. var character = "";
  65547. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  65548. character = String.fromCharCode(uint8array[i]);
  65549. if (character == "\n") {
  65550. break;
  65551. }
  65552. line += character;
  65553. }
  65554. return line;
  65555. };
  65556. /**
  65557. * Reads header information from an RGBE texture stored in a native array.
  65558. * More information on this format are available here:
  65559. * https://en.wikipedia.org/wiki/RGBE_image_format
  65560. *
  65561. * @param uint8array The binary file stored in native array.
  65562. * @return The header information.
  65563. */
  65564. HDRTools.RGBE_ReadHeader = function (uint8array) {
  65565. var height = 0;
  65566. var width = 0;
  65567. var line = this.readStringLine(uint8array, 0);
  65568. if (line[0] != '#' || line[1] != '?') {
  65569. throw "Bad HDR Format.";
  65570. }
  65571. var endOfHeader = false;
  65572. var findFormat = false;
  65573. var lineIndex = 0;
  65574. do {
  65575. lineIndex += (line.length + 1);
  65576. line = this.readStringLine(uint8array, lineIndex);
  65577. if (line == "FORMAT=32-bit_rle_rgbe") {
  65578. findFormat = true;
  65579. }
  65580. else if (line.length == 0) {
  65581. endOfHeader = true;
  65582. }
  65583. } while (!endOfHeader);
  65584. if (!findFormat) {
  65585. throw "HDR Bad header format, unsupported FORMAT";
  65586. }
  65587. lineIndex += (line.length + 1);
  65588. line = this.readStringLine(uint8array, lineIndex);
  65589. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  65590. var match = sizeRegexp.exec(line);
  65591. // TODO. Support +Y and -X if needed.
  65592. if (!match || match.length < 3) {
  65593. throw "HDR Bad header format, no size";
  65594. }
  65595. width = parseInt(match[2]);
  65596. height = parseInt(match[1]);
  65597. if (width < 8 || width > 0x7fff) {
  65598. throw "HDR Bad header format, unsupported size";
  65599. }
  65600. lineIndex += (line.length + 1);
  65601. return {
  65602. height: height,
  65603. width: width,
  65604. dataPosition: lineIndex
  65605. };
  65606. };
  65607. /**
  65608. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  65609. * This RGBE texture needs to store the information as a panorama.
  65610. *
  65611. * More information on this format are available here:
  65612. * https://en.wikipedia.org/wiki/RGBE_image_format
  65613. *
  65614. * @param buffer The binary file stored in an array buffer.
  65615. * @param size The expected size of the extracted cubemap.
  65616. * @return The Cube Map information.
  65617. */
  65618. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  65619. var uint8array = new Uint8Array(buffer);
  65620. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  65621. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  65622. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  65623. return cubeMapData;
  65624. };
  65625. /**
  65626. * Returns the pixels data extracted from an RGBE texture.
  65627. * This pixels will be stored left to right up to down in the R G B order in one array.
  65628. *
  65629. * More information on this format are available here:
  65630. * https://en.wikipedia.org/wiki/RGBE_image_format
  65631. *
  65632. * @param uint8array The binary file stored in an array buffer.
  65633. * @param hdrInfo The header information of the file.
  65634. * @return The pixels data in RGB right to left up to down order.
  65635. */
  65636. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  65637. // Keep for multi format supports.
  65638. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  65639. };
  65640. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  65641. var num_scanlines = hdrInfo.height;
  65642. var scanline_width = hdrInfo.width;
  65643. var a, b, c, d, count;
  65644. var dataIndex = hdrInfo.dataPosition;
  65645. var index = 0, endIndex = 0, i = 0;
  65646. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  65647. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  65648. // 3 channels of 4 bytes per pixel in float.
  65649. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  65650. var resultArray = new Float32Array(resultBuffer);
  65651. // read in each successive scanline
  65652. while (num_scanlines > 0) {
  65653. a = uint8array[dataIndex++];
  65654. b = uint8array[dataIndex++];
  65655. c = uint8array[dataIndex++];
  65656. d = uint8array[dataIndex++];
  65657. if (a != 2 || b != 2 || (c & 0x80)) {
  65658. // this file is not run length encoded
  65659. throw "HDR Bad header format, not RLE";
  65660. }
  65661. if (((c << 8) | d) != scanline_width) {
  65662. throw "HDR Bad header format, wrong scan line width";
  65663. }
  65664. index = 0;
  65665. // read each of the four channels for the scanline into the buffer
  65666. for (i = 0; i < 4; i++) {
  65667. endIndex = (i + 1) * scanline_width;
  65668. while (index < endIndex) {
  65669. a = uint8array[dataIndex++];
  65670. b = uint8array[dataIndex++];
  65671. if (a > 128) {
  65672. // a run of the same value
  65673. count = a - 128;
  65674. if ((count == 0) || (count > endIndex - index)) {
  65675. throw "HDR Bad Format, bad scanline data (run)";
  65676. }
  65677. while (count-- > 0) {
  65678. scanLineArray[index++] = b;
  65679. }
  65680. }
  65681. else {
  65682. // a non-run
  65683. count = a;
  65684. if ((count == 0) || (count > endIndex - index)) {
  65685. throw "HDR Bad Format, bad scanline data (non-run)";
  65686. }
  65687. scanLineArray[index++] = b;
  65688. if (--count > 0) {
  65689. for (var j = 0; j < count; j++) {
  65690. scanLineArray[index++] = uint8array[dataIndex++];
  65691. }
  65692. }
  65693. }
  65694. }
  65695. }
  65696. // now convert data from buffer into floats
  65697. for (i = 0; i < scanline_width; i++) {
  65698. a = scanLineArray[i];
  65699. b = scanLineArray[i + scanline_width];
  65700. c = scanLineArray[i + 2 * scanline_width];
  65701. d = scanLineArray[i + 3 * scanline_width];
  65702. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  65703. }
  65704. num_scanlines--;
  65705. }
  65706. return resultArray;
  65707. };
  65708. return HDRTools;
  65709. }());
  65710. BABYLON.HDRTools = HDRTools;
  65711. })(BABYLON || (BABYLON = {}));
  65712. //# sourceMappingURL=babylon.hdr.js.map
  65713. var BABYLON;
  65714. (function (BABYLON) {
  65715. /**
  65716. * This represents a texture coming from an HDR input.
  65717. *
  65718. * The only supported format is currently panorama picture stored in RGBE format.
  65719. * Example of such files can be found on HDRLib: http://hdrlib.com/
  65720. */
  65721. var HDRCubeTexture = /** @class */ (function (_super) {
  65722. __extends(HDRCubeTexture, _super);
  65723. /**
  65724. * Instantiates an HDRTexture from the following parameters.
  65725. *
  65726. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  65727. * @param scene The scene the texture will be used in
  65728. * @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.
  65729. * @param noMipmap Forces to not generate the mipmap if true
  65730. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  65731. * @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)
  65732. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  65733. */
  65734. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  65735. if (noMipmap === void 0) { noMipmap = false; }
  65736. if (generateHarmonics === void 0) { generateHarmonics = true; }
  65737. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  65738. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  65739. if (onLoad === void 0) { onLoad = null; }
  65740. if (onError === void 0) { onError = null; }
  65741. var _this = _super.call(this, scene) || this;
  65742. _this._useInGammaSpace = false;
  65743. _this._generateHarmonics = true;
  65744. _this._isBABYLONPreprocessed = false;
  65745. _this._onLoad = null;
  65746. _this._onError = null;
  65747. /**
  65748. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  65749. */
  65750. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  65751. /**
  65752. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  65753. * This is usefull at run time to apply the good shader.
  65754. */
  65755. _this.isPMREM = false;
  65756. _this._isBlocking = true;
  65757. if (!url) {
  65758. return _this;
  65759. }
  65760. _this.name = url;
  65761. _this.url = url;
  65762. _this.hasAlpha = false;
  65763. _this.isCube = true;
  65764. _this._textureMatrix = BABYLON.Matrix.Identity();
  65765. _this._onLoad = onLoad;
  65766. _this._onError = onError;
  65767. _this.gammaSpace = false;
  65768. var caps = scene.getEngine().getCaps();
  65769. if (size) {
  65770. _this._isBABYLONPreprocessed = false;
  65771. _this._noMipmap = noMipmap;
  65772. _this._size = size;
  65773. _this._useInGammaSpace = useInGammaSpace;
  65774. _this._usePMREMGenerator = usePMREMGenerator &&
  65775. caps.textureLOD &&
  65776. caps.textureFloat &&
  65777. !_this._useInGammaSpace;
  65778. }
  65779. else {
  65780. _this._isBABYLONPreprocessed = true;
  65781. _this._noMipmap = false;
  65782. _this._useInGammaSpace = false;
  65783. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  65784. !_this._useInGammaSpace;
  65785. }
  65786. _this.isPMREM = _this._usePMREMGenerator;
  65787. _this._texture = _this._getFromCache(url, _this._noMipmap);
  65788. if (!_this._texture) {
  65789. if (!scene.useDelayedTextureLoading) {
  65790. _this.loadTexture();
  65791. }
  65792. else {
  65793. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  65794. }
  65795. }
  65796. return _this;
  65797. }
  65798. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  65799. /**
  65800. * Gets wether or not the texture is blocking during loading.
  65801. */
  65802. get: function () {
  65803. return this._isBlocking;
  65804. },
  65805. /**
  65806. * Sets wether or not the texture is blocking during loading.
  65807. */
  65808. set: function (value) {
  65809. this._isBlocking = value;
  65810. },
  65811. enumerable: true,
  65812. configurable: true
  65813. });
  65814. /**
  65815. * Occurs when the file is a preprocessed .babylon.hdr file.
  65816. */
  65817. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  65818. var _this = this;
  65819. var mipLevels = 0;
  65820. var floatArrayView = null;
  65821. var scene = this.getScene();
  65822. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  65823. var mips = new Array();
  65824. if (!floatArrayView) {
  65825. return mips;
  65826. }
  65827. var startIndex = 30;
  65828. for (var level = 0; level < mipLevels; level++) {
  65829. mips.push([]);
  65830. // Fill each pixel of the mip level.
  65831. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  65832. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65833. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  65834. mips[level].push(faceData);
  65835. startIndex += faceSize;
  65836. }
  65837. }
  65838. return mips;
  65839. } : null;
  65840. var callback = function (buffer) {
  65841. var scene = _this.getScene();
  65842. if (!scene) {
  65843. return null;
  65844. }
  65845. // Create Native Array Views
  65846. var intArrayView = new Int32Array(buffer);
  65847. floatArrayView = new Float32Array(buffer);
  65848. // Fill header.
  65849. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  65850. _this._size = intArrayView[1]; // CubeMap max mip face size.
  65851. // Update Texture Information.
  65852. if (!_this._texture) {
  65853. return null;
  65854. }
  65855. _this._texture.updateSize(_this._size, _this._size);
  65856. // Fill polynomial information.
  65857. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  65858. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  65859. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  65860. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  65861. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  65862. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  65863. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  65864. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  65865. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  65866. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  65867. _this.sphericalPolynomial = sphericalPolynomial;
  65868. // Fill pixel data.
  65869. mipLevels = intArrayView[29]; // Number of mip levels.
  65870. var startIndex = 30;
  65871. var data = [];
  65872. var faceSize = Math.pow(_this._size, 2) * 3;
  65873. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65874. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  65875. startIndex += faceSize;
  65876. }
  65877. var results = [];
  65878. var byteArray = null;
  65879. // Push each faces.
  65880. for (var k = 0; k < 6; k++) {
  65881. var dataFace = null;
  65882. // To be deprecated.
  65883. if (version === 1) {
  65884. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  65885. dataFace = data[j];
  65886. }
  65887. // If special cases.
  65888. if (!mipmapGenerator && dataFace) {
  65889. if (!scene.getEngine().getCaps().textureFloat) {
  65890. // 3 channels of 1 bytes per pixel in bytes.
  65891. var byteBuffer = new ArrayBuffer(faceSize);
  65892. byteArray = new Uint8Array(byteBuffer);
  65893. }
  65894. for (var i = 0; i < _this._size * _this._size; i++) {
  65895. // Put in gamma space if requested.
  65896. if (_this._useInGammaSpace) {
  65897. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  65898. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  65899. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  65900. }
  65901. // Convert to int texture for fallback.
  65902. if (byteArray) {
  65903. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  65904. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  65905. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  65906. // May use luminance instead if the result is not accurate.
  65907. var max = Math.max(Math.max(r, g), b);
  65908. if (max > 255) {
  65909. var scale = 255 / max;
  65910. r *= scale;
  65911. g *= scale;
  65912. b *= scale;
  65913. }
  65914. byteArray[(i * 3) + 0] = r;
  65915. byteArray[(i * 3) + 1] = g;
  65916. byteArray[(i * 3) + 2] = b;
  65917. }
  65918. }
  65919. }
  65920. // Fill the array accordingly.
  65921. if (byteArray) {
  65922. results.push(byteArray);
  65923. }
  65924. else {
  65925. results.push(dataFace);
  65926. }
  65927. }
  65928. return results;
  65929. };
  65930. if (scene) {
  65931. 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);
  65932. }
  65933. };
  65934. /**
  65935. * Occurs when the file is raw .hdr file.
  65936. */
  65937. HDRCubeTexture.prototype.loadHDRTexture = function () {
  65938. var _this = this;
  65939. var callback = function (buffer) {
  65940. var scene = _this.getScene();
  65941. if (!scene) {
  65942. return null;
  65943. }
  65944. // Extract the raw linear data.
  65945. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  65946. // Generate harmonics if needed.
  65947. if (_this._generateHarmonics) {
  65948. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  65949. _this.sphericalPolynomial = sphericalPolynomial;
  65950. }
  65951. var results = [];
  65952. var byteArray = null;
  65953. // Push each faces.
  65954. for (var j = 0; j < 6; j++) {
  65955. // Create uintarray fallback.
  65956. if (!scene.getEngine().getCaps().textureFloat) {
  65957. // 3 channels of 1 bytes per pixel in bytes.
  65958. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  65959. byteArray = new Uint8Array(byteBuffer);
  65960. }
  65961. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  65962. // If special cases.
  65963. if (_this._useInGammaSpace || byteArray) {
  65964. for (var i = 0; i < _this._size * _this._size; i++) {
  65965. // Put in gamma space if requested.
  65966. if (_this._useInGammaSpace) {
  65967. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  65968. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  65969. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  65970. }
  65971. // Convert to int texture for fallback.
  65972. if (byteArray) {
  65973. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  65974. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  65975. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  65976. // May use luminance instead if the result is not accurate.
  65977. var max = Math.max(Math.max(r, g), b);
  65978. if (max > 255) {
  65979. var scale = 255 / max;
  65980. r *= scale;
  65981. g *= scale;
  65982. b *= scale;
  65983. }
  65984. byteArray[(i * 3) + 0] = r;
  65985. byteArray[(i * 3) + 1] = g;
  65986. byteArray[(i * 3) + 2] = b;
  65987. }
  65988. }
  65989. }
  65990. if (byteArray) {
  65991. results.push(byteArray);
  65992. }
  65993. else {
  65994. results.push(dataFace);
  65995. }
  65996. }
  65997. return results;
  65998. };
  65999. var mipmapGenerator = null;
  66000. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  66001. // if (!this._noMipmap &&
  66002. // this._usePMREMGenerator) {
  66003. // mipmapGenerator = (data: ArrayBufferView[]) => {
  66004. // // Custom setup of the generator matching with the PBR shader values.
  66005. // var generator = new BABYLON.PMREMGenerator(data,
  66006. // this._size,
  66007. // this._size,
  66008. // 0,
  66009. // 3,
  66010. // this.getScene().getEngine().getCaps().textureFloat,
  66011. // 2048,
  66012. // 0.25,
  66013. // false,
  66014. // true);
  66015. // return generator.filterCubeMap();
  66016. // };
  66017. // }
  66018. var scene = this.getScene();
  66019. if (scene) {
  66020. 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);
  66021. }
  66022. };
  66023. /**
  66024. * Starts the loading process of the texture.
  66025. */
  66026. HDRCubeTexture.prototype.loadTexture = function () {
  66027. if (this._isBABYLONPreprocessed) {
  66028. this.loadBabylonTexture();
  66029. }
  66030. else {
  66031. this.loadHDRTexture();
  66032. }
  66033. };
  66034. HDRCubeTexture.prototype.clone = function () {
  66035. var scene = this.getScene();
  66036. if (!scene) {
  66037. return this;
  66038. }
  66039. var size = (this._isBABYLONPreprocessed ? null : this._size);
  66040. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  66041. // Base texture
  66042. newTexture.level = this.level;
  66043. newTexture.wrapU = this.wrapU;
  66044. newTexture.wrapV = this.wrapV;
  66045. newTexture.coordinatesIndex = this.coordinatesIndex;
  66046. newTexture.coordinatesMode = this.coordinatesMode;
  66047. return newTexture;
  66048. };
  66049. // Methods
  66050. HDRCubeTexture.prototype.delayLoad = function () {
  66051. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  66052. return;
  66053. }
  66054. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  66055. this._texture = this._getFromCache(this.url, this._noMipmap);
  66056. if (!this._texture) {
  66057. this.loadTexture();
  66058. }
  66059. };
  66060. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  66061. return this._textureMatrix;
  66062. };
  66063. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  66064. this._textureMatrix = value;
  66065. };
  66066. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  66067. var texture = null;
  66068. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  66069. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  66070. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  66071. texture.name = parsedTexture.name;
  66072. texture.hasAlpha = parsedTexture.hasAlpha;
  66073. texture.level = parsedTexture.level;
  66074. texture.coordinatesMode = parsedTexture.coordinatesMode;
  66075. texture.isBlocking = parsedTexture.isBlocking;
  66076. }
  66077. return texture;
  66078. };
  66079. HDRCubeTexture.prototype.serialize = function () {
  66080. if (!this.name) {
  66081. return null;
  66082. }
  66083. var serializationObject = {};
  66084. serializationObject.name = this.name;
  66085. serializationObject.hasAlpha = this.hasAlpha;
  66086. serializationObject.isCube = true;
  66087. serializationObject.level = this.level;
  66088. serializationObject.size = this._size;
  66089. serializationObject.coordinatesMode = this.coordinatesMode;
  66090. serializationObject.useInGammaSpace = this._useInGammaSpace;
  66091. serializationObject.generateHarmonics = this._generateHarmonics;
  66092. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  66093. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  66094. serializationObject.customType = "BABYLON.HDRCubeTexture";
  66095. serializationObject.noMipmap = this._noMipmap;
  66096. serializationObject.isBlocking = this._isBlocking;
  66097. return serializationObject;
  66098. };
  66099. /**
  66100. * Saves as a file the data contained in the texture in a binary format.
  66101. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  66102. * as the spherical used in the lighting.
  66103. * @param url The HDR file url.
  66104. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  66105. * @param onError Method called if any error happens during download.
  66106. * @return The packed binary data.
  66107. */
  66108. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  66109. if (onError === void 0) { onError = null; }
  66110. var callback = function (buffer) {
  66111. var data = new Blob([buffer], { type: 'application/octet-stream' });
  66112. // Returns a URL you can use as a href.
  66113. var objUrl = window.URL.createObjectURL(data);
  66114. // Simulates a link to it and click to dowload.
  66115. var a = document.createElement("a");
  66116. document.body.appendChild(a);
  66117. a.style.display = "none";
  66118. a.href = objUrl;
  66119. a.download = "envmap.babylon.hdr";
  66120. a.click();
  66121. };
  66122. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  66123. };
  66124. /**
  66125. * Serializes the data contained in the texture in a binary format.
  66126. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  66127. * as the spherical used in the lighting.
  66128. * @param url The HDR file url.
  66129. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  66130. * @param onError Method called if any error happens during download.
  66131. * @return The packed binary data.
  66132. */
  66133. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  66134. if (onError === void 0) { onError = null; }
  66135. // Needs the url tho create the texture.
  66136. if (!url) {
  66137. return;
  66138. }
  66139. // Check Power of two size.
  66140. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  66141. return;
  66142. }
  66143. // Coming Back in 3.x.
  66144. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  66145. };
  66146. HDRCubeTexture._facesMapping = [
  66147. "right",
  66148. "left",
  66149. "up",
  66150. "down",
  66151. "front",
  66152. "back"
  66153. ];
  66154. return HDRCubeTexture;
  66155. }(BABYLON.BaseTexture));
  66156. BABYLON.HDRCubeTexture = HDRCubeTexture;
  66157. })(BABYLON || (BABYLON = {}));
  66158. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  66159. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  66160. // Huge respect for a such great lib.
  66161. // Earcut license:
  66162. // Copyright (c) 2016, Mapbox
  66163. //
  66164. // Permission to use, copy, modify, and/or distribute this software for any purpose
  66165. // with or without fee is hereby granted, provided that the above copyright notice
  66166. // and this permission notice appear in all copies.
  66167. //
  66168. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  66169. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  66170. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  66171. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  66172. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  66173. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  66174. // THIS SOFTWARE.
  66175. var Earcut;
  66176. (function (Earcut) {
  66177. /**
  66178. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  66179. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  66180. * @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).
  66181. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  66182. */
  66183. function earcut(data, holeIndices, dim) {
  66184. dim = dim || 2;
  66185. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  66186. if (!outerNode)
  66187. return triangles;
  66188. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  66189. if (hasHoles)
  66190. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  66191. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  66192. if (data.length > 80 * dim) {
  66193. minX = maxX = data[0];
  66194. minY = maxY = data[1];
  66195. for (var i = dim; i < outerLen; i += dim) {
  66196. x = data[i];
  66197. y = data[i + 1];
  66198. if (x < minX)
  66199. minX = x;
  66200. if (y < minY)
  66201. minY = y;
  66202. if (x > maxX)
  66203. maxX = x;
  66204. if (y > maxY)
  66205. maxY = y;
  66206. }
  66207. // minX, minY and size are later used to transform coords into integers for z-order calculation
  66208. size = Math.max(maxX - minX, maxY - minY);
  66209. }
  66210. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  66211. return triangles;
  66212. }
  66213. Earcut.earcut = earcut;
  66214. var Node = /** @class */ (function () {
  66215. function Node(i, x, y) {
  66216. this.i = i;
  66217. this.x = x;
  66218. this.y = y;
  66219. this.prev = null;
  66220. this.next = null;
  66221. this.z = null;
  66222. this.prevZ = null;
  66223. this.nextZ = null;
  66224. this.steiner = false;
  66225. }
  66226. return Node;
  66227. }());
  66228. // create a circular doubly linked list from polygon points in the specified winding order
  66229. function linkedList(data, start, end, dim, clockwise) {
  66230. var i, last = null;
  66231. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  66232. for (i = start; i < end; i += dim)
  66233. last = insertNode(i, data[i], data[i + 1], last);
  66234. }
  66235. else {
  66236. for (i = end - dim; i >= start; i -= dim)
  66237. last = insertNode(i, data[i], data[i + 1], last);
  66238. }
  66239. if (last && equals(last, last.next)) {
  66240. removeNode(last);
  66241. last = last.next;
  66242. }
  66243. return last;
  66244. }
  66245. // eliminate colinear or duplicate points
  66246. function filterPoints(start, end) {
  66247. if (!start)
  66248. return start;
  66249. if (!end)
  66250. end = start;
  66251. var p = start, again;
  66252. do {
  66253. again = false;
  66254. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  66255. removeNode(p);
  66256. p = end = p.prev;
  66257. if (p === p.next)
  66258. return undefined;
  66259. again = true;
  66260. }
  66261. else {
  66262. p = p.next;
  66263. }
  66264. } while (again || p !== end);
  66265. return end;
  66266. }
  66267. // main ear slicing loop which triangulates a polygon (given as a linked list)
  66268. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  66269. if (!ear)
  66270. return;
  66271. // interlink polygon nodes in z-order
  66272. if (!pass && size)
  66273. indexCurve(ear, minX, minY, size);
  66274. var stop = ear, prev, next;
  66275. // iterate through ears, slicing them one by one
  66276. while (ear.prev !== ear.next) {
  66277. prev = ear.prev;
  66278. next = ear.next;
  66279. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  66280. // cut off the triangle
  66281. triangles.push(prev.i / dim);
  66282. triangles.push(ear.i / dim);
  66283. triangles.push(next.i / dim);
  66284. removeNode(ear);
  66285. // skipping the next vertice leads to less sliver triangles
  66286. ear = next.next;
  66287. stop = next.next;
  66288. continue;
  66289. }
  66290. ear = next;
  66291. // if we looped through the whole remaining polygon and can't find any more ears
  66292. if (ear === stop) {
  66293. // try filtering points and slicing again
  66294. if (!pass) {
  66295. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  66296. // if this didn't work, try curing all small self-intersections locally
  66297. }
  66298. else if (pass === 1) {
  66299. ear = cureLocalIntersections(ear, triangles, dim);
  66300. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  66301. // as a last resort, try splitting the remaining polygon into two
  66302. }
  66303. else if (pass === 2) {
  66304. splitEarcut(ear, triangles, dim, minX, minY, size);
  66305. }
  66306. break;
  66307. }
  66308. }
  66309. }
  66310. // check whether a polygon node forms a valid ear with adjacent nodes
  66311. function isEar(ear) {
  66312. var a = ear.prev, b = ear, c = ear.next;
  66313. if (area(a, b, c) >= 0)
  66314. return false; // reflex, can't be an ear
  66315. // now make sure we don't have other points inside the potential ear
  66316. var p = ear.next.next;
  66317. while (p !== ear.prev) {
  66318. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66319. area(p.prev, p, p.next) >= 0)
  66320. return false;
  66321. p = p.next;
  66322. }
  66323. return true;
  66324. }
  66325. function isEarHashed(ear, minX, minY, size) {
  66326. var a = ear.prev, b = ear, c = ear.next;
  66327. if (area(a, b, c) >= 0)
  66328. return false; // reflex, can't be an ear
  66329. // triangle bbox; min & max are calculated like this for speed
  66330. 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);
  66331. // z-order range for the current triangle bbox;
  66332. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  66333. // first look for points inside the triangle in increasing z-order
  66334. var p = ear.nextZ;
  66335. while (p && p.z <= maxZ) {
  66336. if (p !== ear.prev &&
  66337. p !== ear.next &&
  66338. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66339. area(p.prev, p, p.next) >= 0)
  66340. return false;
  66341. p = p.nextZ;
  66342. }
  66343. // then look for points in decreasing z-order
  66344. p = ear.prevZ;
  66345. while (p && p.z >= minZ) {
  66346. if (p !== ear.prev &&
  66347. p !== ear.next &&
  66348. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66349. area(p.prev, p, p.next) >= 0)
  66350. return false;
  66351. p = p.prevZ;
  66352. }
  66353. return true;
  66354. }
  66355. // go through all polygon nodes and cure small local self-intersections
  66356. function cureLocalIntersections(start, triangles, dim) {
  66357. var p = start;
  66358. do {
  66359. var a = p.prev, b = p.next.next;
  66360. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  66361. triangles.push(a.i / dim);
  66362. triangles.push(p.i / dim);
  66363. triangles.push(b.i / dim);
  66364. // remove two nodes involved
  66365. removeNode(p);
  66366. removeNode(p.next);
  66367. p = start = b;
  66368. }
  66369. p = p.next;
  66370. } while (p !== start);
  66371. return p;
  66372. }
  66373. // try splitting polygon into two and triangulate them independently
  66374. function splitEarcut(start, triangles, dim, minX, minY, size) {
  66375. // look for a valid diagonal that divides the polygon into two
  66376. var a = start;
  66377. do {
  66378. var b = a.next.next;
  66379. while (b !== a.prev) {
  66380. if (a.i !== b.i && isValidDiagonal(a, b)) {
  66381. // split the polygon in two by the diagonal
  66382. var c = splitPolygon(a, b);
  66383. // filter colinear points around the cuts
  66384. a = filterPoints(a, a.next);
  66385. c = filterPoints(c, c.next);
  66386. // run earcut on each half
  66387. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  66388. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  66389. return;
  66390. }
  66391. b = b.next;
  66392. }
  66393. a = a.next;
  66394. } while (a !== start);
  66395. }
  66396. // link every hole into the outer loop, producing a single-ring polygon without holes
  66397. function eliminateHoles(data, holeIndices, outerNode, dim) {
  66398. var queue = [], i, len, start, end, list;
  66399. for (i = 0, len = holeIndices.length; i < len; i++) {
  66400. start = holeIndices[i] * dim;
  66401. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66402. list = linkedList(data, start, end, dim, false);
  66403. if (list === list.next)
  66404. list.steiner = true;
  66405. queue.push(getLeftmost(list));
  66406. }
  66407. queue.sort(compareX);
  66408. // process holes from left to right
  66409. for (i = 0; i < queue.length; i++) {
  66410. eliminateHole(queue[i], outerNode);
  66411. outerNode = filterPoints(outerNode, outerNode.next);
  66412. }
  66413. return outerNode;
  66414. }
  66415. function compareX(a, b) {
  66416. return a.x - b.x;
  66417. }
  66418. // find a bridge between vertices that connects hole with an outer ring and and link it
  66419. function eliminateHole(hole, outerNode) {
  66420. outerNode = findHoleBridge(hole, outerNode);
  66421. if (outerNode) {
  66422. var b = splitPolygon(outerNode, hole);
  66423. filterPoints(b, b.next);
  66424. }
  66425. }
  66426. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  66427. function findHoleBridge(hole, outerNode) {
  66428. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  66429. // find a segment intersected by a ray from the hole's leftmost point to the left;
  66430. // segment's endpoint with lesser x will be potential connection point
  66431. do {
  66432. if (hy <= p.y && hy >= p.next.y) {
  66433. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  66434. if (x <= hx && x > qx) {
  66435. qx = x;
  66436. if (x === hx) {
  66437. if (hy === p.y)
  66438. return p;
  66439. if (hy === p.next.y)
  66440. return p.next;
  66441. }
  66442. m = p.x < p.next.x ? p : p.next;
  66443. }
  66444. }
  66445. p = p.next;
  66446. } while (p !== outerNode);
  66447. if (!m)
  66448. return null;
  66449. if (hx === qx)
  66450. return m.prev; // hole touches outer segment; pick lower endpoint
  66451. // look for points inside the triangle of hole point, segment intersection and endpoint;
  66452. // if there are no points found, we have a valid connection;
  66453. // otherwise choose the point of the minimum angle with the ray as connection point
  66454. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  66455. p = m.next;
  66456. while (p !== stop) {
  66457. if (hx >= p.x &&
  66458. p.x >= mx &&
  66459. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  66460. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  66461. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  66462. m = p;
  66463. tanMin = tan;
  66464. }
  66465. }
  66466. p = p.next;
  66467. }
  66468. return m;
  66469. }
  66470. // interlink polygon nodes in z-order
  66471. function indexCurve(start, minX, minY, size) {
  66472. var p = start;
  66473. do {
  66474. if (p.z === null)
  66475. p.z = zOrder(p.x, p.y, minX, minY, size);
  66476. p.prevZ = p.prev;
  66477. p.nextZ = p.next;
  66478. p = p.next;
  66479. } while (p !== start);
  66480. p.prevZ.nextZ = null;
  66481. p.prevZ = null;
  66482. sortLinked(p);
  66483. }
  66484. // Simon Tatham's linked list merge sort algorithm
  66485. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  66486. function sortLinked(list) {
  66487. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  66488. do {
  66489. p = list;
  66490. list = null;
  66491. tail = null;
  66492. numMerges = 0;
  66493. while (p) {
  66494. numMerges++;
  66495. q = p;
  66496. pSize = 0;
  66497. for (i = 0; i < inSize; i++) {
  66498. pSize++;
  66499. q = q.nextZ;
  66500. if (!q)
  66501. break;
  66502. }
  66503. qSize = inSize;
  66504. while (pSize > 0 || (qSize > 0 && q)) {
  66505. if (pSize === 0) {
  66506. e = q;
  66507. q = q.nextZ;
  66508. qSize--;
  66509. }
  66510. else if (qSize === 0 || !q) {
  66511. e = p;
  66512. p = p.nextZ;
  66513. pSize--;
  66514. }
  66515. else if (p.z <= q.z) {
  66516. e = p;
  66517. p = p.nextZ;
  66518. pSize--;
  66519. }
  66520. else {
  66521. e = q;
  66522. q = q.nextZ;
  66523. qSize--;
  66524. }
  66525. if (tail)
  66526. tail.nextZ = e;
  66527. else
  66528. list = e;
  66529. e.prevZ = tail;
  66530. tail = e;
  66531. }
  66532. p = q;
  66533. }
  66534. tail.nextZ = null;
  66535. inSize *= 2;
  66536. } while (numMerges > 1);
  66537. return list;
  66538. }
  66539. // z-order of a point given coords and size of the data bounding box
  66540. function zOrder(x, y, minX, minY, size) {
  66541. // coords are transformed into non-negative 15-bit integer range
  66542. x = 32767 * (x - minX) / size;
  66543. y = 32767 * (y - minY) / size;
  66544. x = (x | (x << 8)) & 0x00FF00FF;
  66545. x = (x | (x << 4)) & 0x0F0F0F0F;
  66546. x = (x | (x << 2)) & 0x33333333;
  66547. x = (x | (x << 1)) & 0x55555555;
  66548. y = (y | (y << 8)) & 0x00FF00FF;
  66549. y = (y | (y << 4)) & 0x0F0F0F0F;
  66550. y = (y | (y << 2)) & 0x33333333;
  66551. y = (y | (y << 1)) & 0x55555555;
  66552. return x | (y << 1);
  66553. }
  66554. // find the leftmost node of a polygon ring
  66555. function getLeftmost(start) {
  66556. var p = start, leftmost = start;
  66557. do {
  66558. if (p.x < leftmost.x)
  66559. leftmost = p;
  66560. p = p.next;
  66561. } while (p !== start);
  66562. return leftmost;
  66563. }
  66564. // check if a point lies within a convex triangle
  66565. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  66566. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  66567. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  66568. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  66569. }
  66570. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  66571. function isValidDiagonal(a, b) {
  66572. return a.next.i !== b.i &&
  66573. a.prev.i !== b.i &&
  66574. !intersectsPolygon(a, b) &&
  66575. locallyInside(a, b) &&
  66576. locallyInside(b, a) &&
  66577. middleInside(a, b);
  66578. }
  66579. // signed area of a triangle
  66580. function area(p, q, r) {
  66581. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  66582. }
  66583. // check if two points are equal
  66584. function equals(p1, p2) {
  66585. return p1.x === p2.x && p1.y === p2.y;
  66586. }
  66587. // check if two segments intersect
  66588. function intersects(p1, q1, p2, q2) {
  66589. if ((equals(p1, q1) && equals(p2, q2)) ||
  66590. (equals(p1, q2) && equals(p2, q1)))
  66591. return true;
  66592. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  66593. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  66594. }
  66595. // check if a polygon diagonal intersects any polygon segments
  66596. function intersectsPolygon(a, b) {
  66597. var p = a;
  66598. do {
  66599. if (p.i !== a.i &&
  66600. p.next.i !== a.i &&
  66601. p.i !== b.i &&
  66602. p.next.i !== b.i &&
  66603. intersects(p, p.next, a, b))
  66604. return true;
  66605. p = p.next;
  66606. } while (p !== a);
  66607. return false;
  66608. }
  66609. // check if a polygon diagonal is locally inside the polygon
  66610. function locallyInside(a, b) {
  66611. return area(a.prev, a, a.next) < 0
  66612. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  66613. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  66614. }
  66615. // check if the middle point of a polygon diagonal is inside the polygon
  66616. function middleInside(a, b) {
  66617. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  66618. do {
  66619. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  66620. inside = !inside;
  66621. p = p.next;
  66622. } while (p !== a);
  66623. return inside;
  66624. }
  66625. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  66626. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  66627. function splitPolygon(a, b) {
  66628. 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;
  66629. a.next = b;
  66630. b.prev = a;
  66631. a2.next = an;
  66632. an.prev = a2;
  66633. b2.next = a2;
  66634. a2.prev = b2;
  66635. bp.next = b2;
  66636. b2.prev = bp;
  66637. return b2;
  66638. }
  66639. // create a node and optionally link it with previous one (in a circular doubly linked list)
  66640. function insertNode(i, x, y, last) {
  66641. var p = new Node(i, x, y);
  66642. if (!last) {
  66643. p.prev = p;
  66644. p.next = p;
  66645. }
  66646. else {
  66647. p.next = last.next;
  66648. p.prev = last;
  66649. last.next.prev = p;
  66650. last.next = p;
  66651. }
  66652. return p;
  66653. }
  66654. function removeNode(p) {
  66655. p.next.prev = p.prev;
  66656. p.prev.next = p.next;
  66657. if (p.prevZ)
  66658. p.prevZ.nextZ = p.nextZ;
  66659. if (p.nextZ)
  66660. p.nextZ.prevZ = p.prevZ;
  66661. }
  66662. /**
  66663. * return a percentage difference between the polygon area and its triangulation area;
  66664. * used to verify correctness of triangulation
  66665. */
  66666. function deviation(data, holeIndices, dim, triangles) {
  66667. var hasHoles = holeIndices && holeIndices.length;
  66668. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  66669. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  66670. if (hasHoles) {
  66671. for (var i = 0, len = holeIndices.length; i < len; i++) {
  66672. var start = holeIndices[i] * dim;
  66673. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66674. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  66675. }
  66676. }
  66677. var trianglesArea = 0;
  66678. for (i = 0; i < triangles.length; i += 3) {
  66679. var a = triangles[i] * dim;
  66680. var b = triangles[i + 1] * dim;
  66681. var c = triangles[i + 2] * dim;
  66682. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  66683. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  66684. }
  66685. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  66686. }
  66687. Earcut.deviation = deviation;
  66688. ;
  66689. function signedArea(data, start, end, dim) {
  66690. var sum = 0;
  66691. for (var i = start, j = end - dim; i < end; i += dim) {
  66692. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  66693. j = i;
  66694. }
  66695. return sum;
  66696. }
  66697. /**
  66698. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  66699. */
  66700. function flatten(data) {
  66701. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  66702. for (var i = 0; i < data.length; i++) {
  66703. for (var j = 0; j < data[i].length; j++) {
  66704. for (var d = 0; d < dim; d++)
  66705. result.vertices.push(data[i][j][d]);
  66706. }
  66707. if (i > 0) {
  66708. holeIndex += data[i - 1].length;
  66709. result.holes.push(holeIndex);
  66710. }
  66711. }
  66712. return result;
  66713. }
  66714. Earcut.flatten = flatten;
  66715. ;
  66716. })(Earcut || (Earcut = {}));
  66717. //# sourceMappingURL=babylon.earcut.js.map
  66718. var BABYLON;
  66719. (function (BABYLON) {
  66720. var IndexedVector2 = /** @class */ (function (_super) {
  66721. __extends(IndexedVector2, _super);
  66722. function IndexedVector2(original, index) {
  66723. var _this = _super.call(this, original.x, original.y) || this;
  66724. _this.index = index;
  66725. return _this;
  66726. }
  66727. return IndexedVector2;
  66728. }(BABYLON.Vector2));
  66729. var PolygonPoints = /** @class */ (function () {
  66730. function PolygonPoints() {
  66731. this.elements = new Array();
  66732. }
  66733. PolygonPoints.prototype.add = function (originalPoints) {
  66734. var _this = this;
  66735. var result = new Array();
  66736. originalPoints.forEach(function (point) {
  66737. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  66738. var newPoint = new IndexedVector2(point, _this.elements.length);
  66739. result.push(newPoint);
  66740. _this.elements.push(newPoint);
  66741. }
  66742. });
  66743. return result;
  66744. };
  66745. PolygonPoints.prototype.computeBounds = function () {
  66746. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66747. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66748. this.elements.forEach(function (point) {
  66749. // x
  66750. if (point.x < lmin.x) {
  66751. lmin.x = point.x;
  66752. }
  66753. else if (point.x > lmax.x) {
  66754. lmax.x = point.x;
  66755. }
  66756. // y
  66757. if (point.y < lmin.y) {
  66758. lmin.y = point.y;
  66759. }
  66760. else if (point.y > lmax.y) {
  66761. lmax.y = point.y;
  66762. }
  66763. });
  66764. return {
  66765. min: lmin,
  66766. max: lmax,
  66767. width: lmax.x - lmin.x,
  66768. height: lmax.y - lmin.y
  66769. };
  66770. };
  66771. return PolygonPoints;
  66772. }());
  66773. var Polygon = /** @class */ (function () {
  66774. function Polygon() {
  66775. }
  66776. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  66777. return [
  66778. new BABYLON.Vector2(xmin, ymin),
  66779. new BABYLON.Vector2(xmax, ymin),
  66780. new BABYLON.Vector2(xmax, ymax),
  66781. new BABYLON.Vector2(xmin, ymax)
  66782. ];
  66783. };
  66784. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  66785. if (cx === void 0) { cx = 0; }
  66786. if (cy === void 0) { cy = 0; }
  66787. if (numberOfSides === void 0) { numberOfSides = 32; }
  66788. var result = new Array();
  66789. var angle = 0;
  66790. var increment = (Math.PI * 2) / numberOfSides;
  66791. for (var i = 0; i < numberOfSides; i++) {
  66792. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  66793. angle -= increment;
  66794. }
  66795. return result;
  66796. };
  66797. Polygon.Parse = function (input) {
  66798. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  66799. var i, result = [];
  66800. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  66801. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  66802. }
  66803. return result;
  66804. };
  66805. Polygon.StartingAt = function (x, y) {
  66806. return BABYLON.Path2.StartingAt(x, y);
  66807. };
  66808. return Polygon;
  66809. }());
  66810. BABYLON.Polygon = Polygon;
  66811. var PolygonMeshBuilder = /** @class */ (function () {
  66812. function PolygonMeshBuilder(name, contours, scene) {
  66813. this._points = new PolygonPoints();
  66814. this._outlinepoints = new PolygonPoints();
  66815. this._holes = new Array();
  66816. this._epoints = new Array();
  66817. this._eholes = new Array();
  66818. this._name = name;
  66819. this._scene = scene;
  66820. var points;
  66821. if (contours instanceof BABYLON.Path2) {
  66822. points = contours.getPoints();
  66823. }
  66824. else {
  66825. points = contours;
  66826. }
  66827. this._addToepoint(points);
  66828. this._points.add(points);
  66829. this._outlinepoints.add(points);
  66830. }
  66831. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  66832. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  66833. var p = points_1[_i];
  66834. this._epoints.push(p.x, p.y);
  66835. }
  66836. };
  66837. PolygonMeshBuilder.prototype.addHole = function (hole) {
  66838. this._points.add(hole);
  66839. var holepoints = new PolygonPoints();
  66840. holepoints.add(hole);
  66841. this._holes.push(holepoints);
  66842. this._eholes.push(this._epoints.length / 2);
  66843. this._addToepoint(hole);
  66844. return this;
  66845. };
  66846. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  66847. var _this = this;
  66848. if (updatable === void 0) { updatable = false; }
  66849. if (depth === void 0) { depth = 0; }
  66850. var result = new BABYLON.Mesh(this._name, this._scene);
  66851. var normals = new Array();
  66852. var positions = new Array();
  66853. var uvs = new Array();
  66854. var bounds = this._points.computeBounds();
  66855. this._points.elements.forEach(function (p) {
  66856. normals.push(0, 1.0, 0);
  66857. positions.push(p.x, 0, p.y);
  66858. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  66859. });
  66860. var indices = new Array();
  66861. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  66862. for (var i = 0; i < res.length; i++) {
  66863. indices.push(res[i]);
  66864. }
  66865. if (depth > 0) {
  66866. var positionscount = (positions.length / 3); //get the current pointcount
  66867. this._points.elements.forEach(function (p) {
  66868. normals.push(0, -1.0, 0);
  66869. positions.push(p.x, -depth, p.y);
  66870. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  66871. });
  66872. var totalCount = indices.length;
  66873. for (var i = 0; i < totalCount; i += 3) {
  66874. var i0 = indices[i + 0];
  66875. var i1 = indices[i + 1];
  66876. var i2 = indices[i + 2];
  66877. indices.push(i2 + positionscount);
  66878. indices.push(i1 + positionscount);
  66879. indices.push(i0 + positionscount);
  66880. }
  66881. //Add the sides
  66882. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  66883. this._holes.forEach(function (hole) {
  66884. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  66885. });
  66886. }
  66887. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  66888. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  66889. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  66890. result.setIndices(indices);
  66891. return result;
  66892. };
  66893. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  66894. var StartIndex = positions.length / 3;
  66895. var ulength = 0;
  66896. for (var i = 0; i < points.elements.length; i++) {
  66897. var p = points.elements[i];
  66898. var p1;
  66899. if ((i + 1) > points.elements.length - 1) {
  66900. p1 = points.elements[0];
  66901. }
  66902. else {
  66903. p1 = points.elements[i + 1];
  66904. }
  66905. positions.push(p.x, 0, p.y);
  66906. positions.push(p.x, -depth, p.y);
  66907. positions.push(p1.x, 0, p1.y);
  66908. positions.push(p1.x, -depth, p1.y);
  66909. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  66910. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  66911. var v3 = v2.subtract(v1);
  66912. var v4 = new BABYLON.Vector3(0, 1, 0);
  66913. var vn = BABYLON.Vector3.Cross(v3, v4);
  66914. vn = vn.normalize();
  66915. uvs.push(ulength / bounds.width, 0);
  66916. uvs.push(ulength / bounds.width, 1);
  66917. ulength += v3.length();
  66918. uvs.push((ulength / bounds.width), 0);
  66919. uvs.push((ulength / bounds.width), 1);
  66920. if (!flip) {
  66921. normals.push(-vn.x, -vn.y, -vn.z);
  66922. normals.push(-vn.x, -vn.y, -vn.z);
  66923. normals.push(-vn.x, -vn.y, -vn.z);
  66924. normals.push(-vn.x, -vn.y, -vn.z);
  66925. indices.push(StartIndex);
  66926. indices.push(StartIndex + 1);
  66927. indices.push(StartIndex + 2);
  66928. indices.push(StartIndex + 1);
  66929. indices.push(StartIndex + 3);
  66930. indices.push(StartIndex + 2);
  66931. }
  66932. else {
  66933. normals.push(vn.x, vn.y, vn.z);
  66934. normals.push(vn.x, vn.y, vn.z);
  66935. normals.push(vn.x, vn.y, vn.z);
  66936. normals.push(vn.x, vn.y, vn.z);
  66937. indices.push(StartIndex);
  66938. indices.push(StartIndex + 2);
  66939. indices.push(StartIndex + 1);
  66940. indices.push(StartIndex + 1);
  66941. indices.push(StartIndex + 2);
  66942. indices.push(StartIndex + 3);
  66943. }
  66944. StartIndex += 4;
  66945. }
  66946. ;
  66947. };
  66948. return PolygonMeshBuilder;
  66949. }());
  66950. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  66951. })(BABYLON || (BABYLON = {}));
  66952. //# sourceMappingURL=babylon.polygonMesh.js.map
  66953. var BABYLON;
  66954. (function (BABYLON) {
  66955. // Unique ID when we import meshes from Babylon to CSG
  66956. var currentCSGMeshId = 0;
  66957. // # class Vertex
  66958. // Represents a vertex of a polygon. Use your own vertex class instead of this
  66959. // one to provide additional features like texture coordinates and vertex
  66960. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  66961. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  66962. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  66963. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  66964. // is not used anywhere else.
  66965. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  66966. var Vertex = /** @class */ (function () {
  66967. function Vertex(pos, normal, uv) {
  66968. this.pos = pos;
  66969. this.normal = normal;
  66970. this.uv = uv;
  66971. }
  66972. Vertex.prototype.clone = function () {
  66973. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  66974. };
  66975. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  66976. // orientation of a polygon is flipped.
  66977. Vertex.prototype.flip = function () {
  66978. this.normal = this.normal.scale(-1);
  66979. };
  66980. // Create a new vertex between this vertex and `other` by linearly
  66981. // interpolating all properties using a parameter of `t`. Subclasses should
  66982. // override this to interpolate additional properties.
  66983. Vertex.prototype.interpolate = function (other, t) {
  66984. 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));
  66985. };
  66986. return Vertex;
  66987. }());
  66988. // # class Plane
  66989. // Represents a plane in 3D space.
  66990. var Plane = /** @class */ (function () {
  66991. function Plane(normal, w) {
  66992. this.normal = normal;
  66993. this.w = w;
  66994. }
  66995. Plane.FromPoints = function (a, b, c) {
  66996. var v0 = c.subtract(a);
  66997. var v1 = b.subtract(a);
  66998. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  66999. return null;
  67000. }
  67001. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  67002. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  67003. };
  67004. Plane.prototype.clone = function () {
  67005. return new Plane(this.normal.clone(), this.w);
  67006. };
  67007. Plane.prototype.flip = function () {
  67008. this.normal.scaleInPlace(-1);
  67009. this.w = -this.w;
  67010. };
  67011. // Split `polygon` by this plane if needed, then put the polygon or polygon
  67012. // fragments in the appropriate lists. Coplanar polygons go into either
  67013. // `coplanarFront` or `coplanarBack` depending on their orientation with
  67014. // respect to this plane. Polygons in front or in back of this plane go into
  67015. // either `front` or `back`.
  67016. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  67017. var COPLANAR = 0;
  67018. var FRONT = 1;
  67019. var BACK = 2;
  67020. var SPANNING = 3;
  67021. // Classify each point as well as the entire polygon into one of the above
  67022. // four classes.
  67023. var polygonType = 0;
  67024. var types = [];
  67025. var i;
  67026. var t;
  67027. for (i = 0; i < polygon.vertices.length; i++) {
  67028. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  67029. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  67030. polygonType |= type;
  67031. types.push(type);
  67032. }
  67033. // Put the polygon in the correct list, splitting it when necessary.
  67034. switch (polygonType) {
  67035. case COPLANAR:
  67036. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  67037. break;
  67038. case FRONT:
  67039. front.push(polygon);
  67040. break;
  67041. case BACK:
  67042. back.push(polygon);
  67043. break;
  67044. case SPANNING:
  67045. var f = [], b = [];
  67046. for (i = 0; i < polygon.vertices.length; i++) {
  67047. var j = (i + 1) % polygon.vertices.length;
  67048. var ti = types[i], tj = types[j];
  67049. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  67050. if (ti !== BACK)
  67051. f.push(vi);
  67052. if (ti !== FRONT)
  67053. b.push(ti !== BACK ? vi.clone() : vi);
  67054. if ((ti | tj) === SPANNING) {
  67055. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  67056. var v = vi.interpolate(vj, t);
  67057. f.push(v);
  67058. b.push(v.clone());
  67059. }
  67060. }
  67061. var poly;
  67062. if (f.length >= 3) {
  67063. poly = new Polygon(f, polygon.shared);
  67064. if (poly.plane)
  67065. front.push(poly);
  67066. }
  67067. if (b.length >= 3) {
  67068. poly = new Polygon(b, polygon.shared);
  67069. if (poly.plane)
  67070. back.push(poly);
  67071. }
  67072. break;
  67073. }
  67074. };
  67075. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  67076. // point is on the plane.
  67077. Plane.EPSILON = 1e-5;
  67078. return Plane;
  67079. }());
  67080. // # class Polygon
  67081. // Represents a convex polygon. The vertices used to initialize a polygon must
  67082. // be coplanar and form a convex loop.
  67083. //
  67084. // Each convex polygon has a `shared` property, which is shared between all
  67085. // polygons that are clones of each other or were split from the same polygon.
  67086. // This can be used to define per-polygon properties (such as surface color).
  67087. var Polygon = /** @class */ (function () {
  67088. function Polygon(vertices, shared) {
  67089. this.vertices = vertices;
  67090. this.shared = shared;
  67091. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  67092. }
  67093. Polygon.prototype.clone = function () {
  67094. var vertices = this.vertices.map(function (v) { return v.clone(); });
  67095. return new Polygon(vertices, this.shared);
  67096. };
  67097. Polygon.prototype.flip = function () {
  67098. this.vertices.reverse().map(function (v) { v.flip(); });
  67099. this.plane.flip();
  67100. };
  67101. return Polygon;
  67102. }());
  67103. // # class Node
  67104. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  67105. // by picking a polygon to split along. That polygon (and all other coplanar
  67106. // polygons) are added directly to that node and the other polygons are added to
  67107. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  67108. // no distinction between internal and leaf nodes.
  67109. var Node = /** @class */ (function () {
  67110. function Node(polygons) {
  67111. this.plane = null;
  67112. this.front = null;
  67113. this.back = null;
  67114. this.polygons = new Array();
  67115. if (polygons) {
  67116. this.build(polygons);
  67117. }
  67118. }
  67119. Node.prototype.clone = function () {
  67120. var node = new Node();
  67121. node.plane = this.plane && this.plane.clone();
  67122. node.front = this.front && this.front.clone();
  67123. node.back = this.back && this.back.clone();
  67124. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  67125. return node;
  67126. };
  67127. // Convert solid space to empty space and empty space to solid space.
  67128. Node.prototype.invert = function () {
  67129. for (var i = 0; i < this.polygons.length; i++) {
  67130. this.polygons[i].flip();
  67131. }
  67132. if (this.plane) {
  67133. this.plane.flip();
  67134. }
  67135. if (this.front) {
  67136. this.front.invert();
  67137. }
  67138. if (this.back) {
  67139. this.back.invert();
  67140. }
  67141. var temp = this.front;
  67142. this.front = this.back;
  67143. this.back = temp;
  67144. };
  67145. // Recursively remove all polygons in `polygons` that are inside this BSP
  67146. // tree.
  67147. Node.prototype.clipPolygons = function (polygons) {
  67148. if (!this.plane)
  67149. return polygons.slice();
  67150. var front = new Array(), back = new Array();
  67151. for (var i = 0; i < polygons.length; i++) {
  67152. this.plane.splitPolygon(polygons[i], front, back, front, back);
  67153. }
  67154. if (this.front) {
  67155. front = this.front.clipPolygons(front);
  67156. }
  67157. if (this.back) {
  67158. back = this.back.clipPolygons(back);
  67159. }
  67160. else {
  67161. back = [];
  67162. }
  67163. return front.concat(back);
  67164. };
  67165. // Remove all polygons in this BSP tree that are inside the other BSP tree
  67166. // `bsp`.
  67167. Node.prototype.clipTo = function (bsp) {
  67168. this.polygons = bsp.clipPolygons(this.polygons);
  67169. if (this.front)
  67170. this.front.clipTo(bsp);
  67171. if (this.back)
  67172. this.back.clipTo(bsp);
  67173. };
  67174. // Return a list of all polygons in this BSP tree.
  67175. Node.prototype.allPolygons = function () {
  67176. var polygons = this.polygons.slice();
  67177. if (this.front)
  67178. polygons = polygons.concat(this.front.allPolygons());
  67179. if (this.back)
  67180. polygons = polygons.concat(this.back.allPolygons());
  67181. return polygons;
  67182. };
  67183. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  67184. // new polygons are filtered down to the bottom of the tree and become new
  67185. // nodes there. Each set of polygons is partitioned using the first polygon
  67186. // (no heuristic is used to pick a good split).
  67187. Node.prototype.build = function (polygons) {
  67188. if (!polygons.length)
  67189. return;
  67190. if (!this.plane)
  67191. this.plane = polygons[0].plane.clone();
  67192. var front = new Array(), back = new Array();
  67193. for (var i = 0; i < polygons.length; i++) {
  67194. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  67195. }
  67196. if (front.length) {
  67197. if (!this.front)
  67198. this.front = new Node();
  67199. this.front.build(front);
  67200. }
  67201. if (back.length) {
  67202. if (!this.back)
  67203. this.back = new Node();
  67204. this.back.build(back);
  67205. }
  67206. };
  67207. return Node;
  67208. }());
  67209. var CSG = /** @class */ (function () {
  67210. function CSG() {
  67211. this.polygons = new Array();
  67212. }
  67213. // Convert BABYLON.Mesh to BABYLON.CSG
  67214. CSG.FromMesh = function (mesh) {
  67215. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  67216. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  67217. if (mesh instanceof BABYLON.Mesh) {
  67218. mesh.computeWorldMatrix(true);
  67219. matrix = mesh.getWorldMatrix();
  67220. meshPosition = mesh.position.clone();
  67221. meshRotation = mesh.rotation.clone();
  67222. if (mesh.rotationQuaternion) {
  67223. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  67224. }
  67225. meshScaling = mesh.scaling.clone();
  67226. }
  67227. else {
  67228. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  67229. }
  67230. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67231. var subMeshes = mesh.subMeshes;
  67232. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  67233. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  67234. vertices = [];
  67235. for (var j = 0; j < 3; j++) {
  67236. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  67237. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  67238. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  67239. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  67240. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  67241. vertex = new Vertex(position, normal, uv);
  67242. vertices.push(vertex);
  67243. }
  67244. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  67245. // To handle the case of degenerated triangle
  67246. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  67247. if (polygon.plane)
  67248. polygons.push(polygon);
  67249. }
  67250. }
  67251. var csg = CSG.FromPolygons(polygons);
  67252. csg.matrix = matrix;
  67253. csg.position = meshPosition;
  67254. csg.rotation = meshRotation;
  67255. csg.scaling = meshScaling;
  67256. csg.rotationQuaternion = meshRotationQuaternion;
  67257. currentCSGMeshId++;
  67258. return csg;
  67259. };
  67260. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  67261. CSG.FromPolygons = function (polygons) {
  67262. var csg = new CSG();
  67263. csg.polygons = polygons;
  67264. return csg;
  67265. };
  67266. CSG.prototype.clone = function () {
  67267. var csg = new CSG();
  67268. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  67269. csg.copyTransformAttributes(this);
  67270. return csg;
  67271. };
  67272. CSG.prototype.union = function (csg) {
  67273. var a = new Node(this.clone().polygons);
  67274. var b = new Node(csg.clone().polygons);
  67275. a.clipTo(b);
  67276. b.clipTo(a);
  67277. b.invert();
  67278. b.clipTo(a);
  67279. b.invert();
  67280. a.build(b.allPolygons());
  67281. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67282. };
  67283. CSG.prototype.unionInPlace = function (csg) {
  67284. var a = new Node(this.polygons);
  67285. var b = new Node(csg.polygons);
  67286. a.clipTo(b);
  67287. b.clipTo(a);
  67288. b.invert();
  67289. b.clipTo(a);
  67290. b.invert();
  67291. a.build(b.allPolygons());
  67292. this.polygons = a.allPolygons();
  67293. };
  67294. CSG.prototype.subtract = function (csg) {
  67295. var a = new Node(this.clone().polygons);
  67296. var b = new Node(csg.clone().polygons);
  67297. a.invert();
  67298. a.clipTo(b);
  67299. b.clipTo(a);
  67300. b.invert();
  67301. b.clipTo(a);
  67302. b.invert();
  67303. a.build(b.allPolygons());
  67304. a.invert();
  67305. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67306. };
  67307. CSG.prototype.subtractInPlace = function (csg) {
  67308. var a = new Node(this.polygons);
  67309. var b = new Node(csg.polygons);
  67310. a.invert();
  67311. a.clipTo(b);
  67312. b.clipTo(a);
  67313. b.invert();
  67314. b.clipTo(a);
  67315. b.invert();
  67316. a.build(b.allPolygons());
  67317. a.invert();
  67318. this.polygons = a.allPolygons();
  67319. };
  67320. CSG.prototype.intersect = function (csg) {
  67321. var a = new Node(this.clone().polygons);
  67322. var b = new Node(csg.clone().polygons);
  67323. a.invert();
  67324. b.clipTo(a);
  67325. b.invert();
  67326. a.clipTo(b);
  67327. b.clipTo(a);
  67328. a.build(b.allPolygons());
  67329. a.invert();
  67330. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67331. };
  67332. CSG.prototype.intersectInPlace = function (csg) {
  67333. var a = new Node(this.polygons);
  67334. var b = new Node(csg.polygons);
  67335. a.invert();
  67336. b.clipTo(a);
  67337. b.invert();
  67338. a.clipTo(b);
  67339. b.clipTo(a);
  67340. a.build(b.allPolygons());
  67341. a.invert();
  67342. this.polygons = a.allPolygons();
  67343. };
  67344. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  67345. // not modified.
  67346. CSG.prototype.inverse = function () {
  67347. var csg = this.clone();
  67348. csg.inverseInPlace();
  67349. return csg;
  67350. };
  67351. CSG.prototype.inverseInPlace = function () {
  67352. this.polygons.map(function (p) { p.flip(); });
  67353. };
  67354. // This is used to keep meshes transformations so they can be restored
  67355. // when we build back a Babylon Mesh
  67356. // NB : All CSG operations are performed in world coordinates
  67357. CSG.prototype.copyTransformAttributes = function (csg) {
  67358. this.matrix = csg.matrix;
  67359. this.position = csg.position;
  67360. this.rotation = csg.rotation;
  67361. this.scaling = csg.scaling;
  67362. this.rotationQuaternion = csg.rotationQuaternion;
  67363. return this;
  67364. };
  67365. // Build Raw mesh from CSG
  67366. // Coordinates here are in world space
  67367. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  67368. var matrix = this.matrix.clone();
  67369. matrix.invert();
  67370. 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;
  67371. if (keepSubMeshes) {
  67372. // Sort Polygons, since subMeshes are indices range
  67373. polygons.sort(function (a, b) {
  67374. if (a.shared.meshId === b.shared.meshId) {
  67375. return a.shared.subMeshId - b.shared.subMeshId;
  67376. }
  67377. else {
  67378. return a.shared.meshId - b.shared.meshId;
  67379. }
  67380. });
  67381. }
  67382. for (var i = 0, il = polygons.length; i < il; i++) {
  67383. polygon = polygons[i];
  67384. // Building SubMeshes
  67385. if (!subMesh_dict[polygon.shared.meshId]) {
  67386. subMesh_dict[polygon.shared.meshId] = {};
  67387. }
  67388. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  67389. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  67390. indexStart: +Infinity,
  67391. indexEnd: -Infinity,
  67392. materialIndex: polygon.shared.materialIndex
  67393. };
  67394. }
  67395. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  67396. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  67397. polygonIndices[0] = 0;
  67398. polygonIndices[1] = j - 1;
  67399. polygonIndices[2] = j;
  67400. for (var k = 0; k < 3; k++) {
  67401. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  67402. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  67403. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  67404. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  67405. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  67406. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  67407. // Check if 2 points can be merged
  67408. if (!(typeof vertex_idx !== 'undefined' &&
  67409. normals[vertex_idx * 3] === localNormal.x &&
  67410. normals[vertex_idx * 3 + 1] === localNormal.y &&
  67411. normals[vertex_idx * 3 + 2] === localNormal.z &&
  67412. uvs[vertex_idx * 2] === uv.x &&
  67413. uvs[vertex_idx * 2 + 1] === uv.y)) {
  67414. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  67415. uvs.push(uv.x, uv.y);
  67416. normals.push(normal.x, normal.y, normal.z);
  67417. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  67418. }
  67419. indices.push(vertex_idx);
  67420. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  67421. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  67422. currentIndex++;
  67423. }
  67424. }
  67425. }
  67426. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  67427. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  67428. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  67429. mesh.setIndices(indices, null);
  67430. if (keepSubMeshes) {
  67431. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  67432. var materialIndexOffset = 0, materialMaxIndex;
  67433. mesh.subMeshes = new Array();
  67434. for (var m in subMesh_dict) {
  67435. materialMaxIndex = -1;
  67436. for (var sm in subMesh_dict[m]) {
  67437. subMesh_obj = subMesh_dict[m][sm];
  67438. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  67439. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  67440. }
  67441. materialIndexOffset += ++materialMaxIndex;
  67442. }
  67443. }
  67444. return mesh;
  67445. };
  67446. // Build Mesh from CSG taking material and transforms into account
  67447. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  67448. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  67449. mesh.material = material;
  67450. mesh.position.copyFrom(this.position);
  67451. mesh.rotation.copyFrom(this.rotation);
  67452. if (this.rotationQuaternion) {
  67453. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  67454. }
  67455. mesh.scaling.copyFrom(this.scaling);
  67456. mesh.computeWorldMatrix(true);
  67457. return mesh;
  67458. };
  67459. return CSG;
  67460. }());
  67461. BABYLON.CSG = CSG;
  67462. })(BABYLON || (BABYLON = {}));
  67463. //# sourceMappingURL=babylon.csg.js.map
  67464. var BABYLON;
  67465. (function (BABYLON) {
  67466. var LensFlare = /** @class */ (function () {
  67467. function LensFlare(size, position, color, imgUrl, system) {
  67468. this.size = size;
  67469. this.position = position;
  67470. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  67471. this.color = color || new BABYLON.Color3(1, 1, 1);
  67472. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  67473. this._system = system;
  67474. system.lensFlares.push(this);
  67475. }
  67476. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  67477. return new LensFlare(size, position, color, imgUrl, system);
  67478. };
  67479. LensFlare.prototype.dispose = function () {
  67480. if (this.texture) {
  67481. this.texture.dispose();
  67482. }
  67483. // Remove from scene
  67484. var index = this._system.lensFlares.indexOf(this);
  67485. this._system.lensFlares.splice(index, 1);
  67486. };
  67487. ;
  67488. return LensFlare;
  67489. }());
  67490. BABYLON.LensFlare = LensFlare;
  67491. })(BABYLON || (BABYLON = {}));
  67492. //# sourceMappingURL=babylon.lensFlare.js.map
  67493. var BABYLON;
  67494. (function (BABYLON) {
  67495. var LensFlareSystem = /** @class */ (function () {
  67496. function LensFlareSystem(name, emitter, scene) {
  67497. this.name = name;
  67498. this.lensFlares = new Array();
  67499. this.borderLimit = 300;
  67500. this.viewportBorder = 0;
  67501. this.layerMask = 0x0FFFFFFF;
  67502. this._vertexBuffers = {};
  67503. this._isEnabled = true;
  67504. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67505. this._emitter = emitter;
  67506. this.id = name;
  67507. scene.lensFlareSystems.push(this);
  67508. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  67509. var engine = scene.getEngine();
  67510. // VBO
  67511. var vertices = [];
  67512. vertices.push(1, 1);
  67513. vertices.push(-1, 1);
  67514. vertices.push(-1, -1);
  67515. vertices.push(1, -1);
  67516. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67517. // Indices
  67518. var indices = [];
  67519. indices.push(0);
  67520. indices.push(1);
  67521. indices.push(2);
  67522. indices.push(0);
  67523. indices.push(2);
  67524. indices.push(3);
  67525. this._indexBuffer = engine.createIndexBuffer(indices);
  67526. // Effects
  67527. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  67528. }
  67529. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  67530. get: function () {
  67531. return this._isEnabled;
  67532. },
  67533. set: function (value) {
  67534. this._isEnabled = value;
  67535. },
  67536. enumerable: true,
  67537. configurable: true
  67538. });
  67539. LensFlareSystem.prototype.getScene = function () {
  67540. return this._scene;
  67541. };
  67542. LensFlareSystem.prototype.getEmitter = function () {
  67543. return this._emitter;
  67544. };
  67545. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  67546. this._emitter = newEmitter;
  67547. };
  67548. LensFlareSystem.prototype.getEmitterPosition = function () {
  67549. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  67550. };
  67551. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  67552. var position = this.getEmitterPosition();
  67553. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  67554. this._positionX = position.x;
  67555. this._positionY = position.y;
  67556. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  67557. if (this.viewportBorder > 0) {
  67558. globalViewport.x -= this.viewportBorder;
  67559. globalViewport.y -= this.viewportBorder;
  67560. globalViewport.width += this.viewportBorder * 2;
  67561. globalViewport.height += this.viewportBorder * 2;
  67562. position.x += this.viewportBorder;
  67563. position.y += this.viewportBorder;
  67564. this._positionX += this.viewportBorder;
  67565. this._positionY += this.viewportBorder;
  67566. }
  67567. if (position.z > 0) {
  67568. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  67569. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  67570. return true;
  67571. }
  67572. return true;
  67573. }
  67574. return false;
  67575. };
  67576. LensFlareSystem.prototype._isVisible = function () {
  67577. if (!this._isEnabled || !this._scene.activeCamera) {
  67578. return false;
  67579. }
  67580. var emitterPosition = this.getEmitterPosition();
  67581. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  67582. var distance = direction.length();
  67583. direction.normalize();
  67584. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  67585. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  67586. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  67587. };
  67588. LensFlareSystem.prototype.render = function () {
  67589. if (!this._effect.isReady() || !this._scene.activeCamera)
  67590. return false;
  67591. var engine = this._scene.getEngine();
  67592. var viewport = this._scene.activeCamera.viewport;
  67593. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  67594. // Position
  67595. if (!this.computeEffectivePosition(globalViewport)) {
  67596. return false;
  67597. }
  67598. // Visibility
  67599. if (!this._isVisible()) {
  67600. return false;
  67601. }
  67602. // Intensity
  67603. var awayX;
  67604. var awayY;
  67605. if (this._positionX < this.borderLimit + globalViewport.x) {
  67606. awayX = this.borderLimit + globalViewport.x - this._positionX;
  67607. }
  67608. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  67609. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  67610. }
  67611. else {
  67612. awayX = 0;
  67613. }
  67614. if (this._positionY < this.borderLimit + globalViewport.y) {
  67615. awayY = this.borderLimit + globalViewport.y - this._positionY;
  67616. }
  67617. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  67618. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  67619. }
  67620. else {
  67621. awayY = 0;
  67622. }
  67623. var away = (awayX > awayY) ? awayX : awayY;
  67624. away -= this.viewportBorder;
  67625. if (away > this.borderLimit) {
  67626. away = this.borderLimit;
  67627. }
  67628. var intensity = 1.0 - (away / this.borderLimit);
  67629. if (intensity < 0) {
  67630. return false;
  67631. }
  67632. if (intensity > 1.0) {
  67633. intensity = 1.0;
  67634. }
  67635. if (this.viewportBorder > 0) {
  67636. globalViewport.x += this.viewportBorder;
  67637. globalViewport.y += this.viewportBorder;
  67638. globalViewport.width -= this.viewportBorder * 2;
  67639. globalViewport.height -= this.viewportBorder * 2;
  67640. this._positionX -= this.viewportBorder;
  67641. this._positionY -= this.viewportBorder;
  67642. }
  67643. // Position
  67644. var centerX = globalViewport.x + globalViewport.width / 2;
  67645. var centerY = globalViewport.y + globalViewport.height / 2;
  67646. var distX = centerX - this._positionX;
  67647. var distY = centerY - this._positionY;
  67648. // Effects
  67649. engine.enableEffect(this._effect);
  67650. engine.setState(false);
  67651. engine.setDepthBuffer(false);
  67652. // VBOs
  67653. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  67654. // Flares
  67655. for (var index = 0; index < this.lensFlares.length; index++) {
  67656. var flare = this.lensFlares[index];
  67657. engine.setAlphaMode(flare.alphaMode);
  67658. var x = centerX - (distX * flare.position);
  67659. var y = centerY - (distY * flare.position);
  67660. var cw = flare.size;
  67661. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  67662. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  67663. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  67664. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  67665. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  67666. // Texture
  67667. this._effect.setTexture("textureSampler", flare.texture);
  67668. // Color
  67669. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  67670. // Draw order
  67671. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67672. }
  67673. engine.setDepthBuffer(true);
  67674. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67675. return true;
  67676. };
  67677. LensFlareSystem.prototype.dispose = function () {
  67678. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67679. if (vertexBuffer) {
  67680. vertexBuffer.dispose();
  67681. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67682. }
  67683. if (this._indexBuffer) {
  67684. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67685. this._indexBuffer = null;
  67686. }
  67687. while (this.lensFlares.length) {
  67688. this.lensFlares[0].dispose();
  67689. }
  67690. // Remove from scene
  67691. var index = this._scene.lensFlareSystems.indexOf(this);
  67692. this._scene.lensFlareSystems.splice(index, 1);
  67693. };
  67694. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  67695. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  67696. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  67697. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  67698. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  67699. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  67700. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  67701. var parsedFlare = parsedLensFlareSystem.flares[index];
  67702. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  67703. }
  67704. return lensFlareSystem;
  67705. };
  67706. LensFlareSystem.prototype.serialize = function () {
  67707. var serializationObject = {};
  67708. serializationObject.id = this.id;
  67709. serializationObject.name = this.name;
  67710. serializationObject.emitterId = this.getEmitter().id;
  67711. serializationObject.borderLimit = this.borderLimit;
  67712. serializationObject.flares = [];
  67713. for (var index = 0; index < this.lensFlares.length; index++) {
  67714. var flare = this.lensFlares[index];
  67715. serializationObject.flares.push({
  67716. size: flare.size,
  67717. position: flare.position,
  67718. color: flare.color.asArray(),
  67719. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  67720. });
  67721. }
  67722. return serializationObject;
  67723. };
  67724. return LensFlareSystem;
  67725. }());
  67726. BABYLON.LensFlareSystem = LensFlareSystem;
  67727. })(BABYLON || (BABYLON = {}));
  67728. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  67729. var BABYLON;
  67730. (function (BABYLON) {
  67731. /**
  67732. * This is a holder class for the physics joint created by the physics plugin.
  67733. * It holds a set of functions to control the underlying joint.
  67734. */
  67735. var PhysicsJoint = /** @class */ (function () {
  67736. function PhysicsJoint(type, jointData) {
  67737. this.type = type;
  67738. this.jointData = jointData;
  67739. jointData.nativeParams = jointData.nativeParams || {};
  67740. }
  67741. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  67742. get: function () {
  67743. return this._physicsJoint;
  67744. },
  67745. set: function (newJoint) {
  67746. if (this._physicsJoint) {
  67747. //remove from the wolrd
  67748. }
  67749. this._physicsJoint = newJoint;
  67750. },
  67751. enumerable: true,
  67752. configurable: true
  67753. });
  67754. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  67755. set: function (physicsPlugin) {
  67756. this._physicsPlugin = physicsPlugin;
  67757. },
  67758. enumerable: true,
  67759. configurable: true
  67760. });
  67761. /**
  67762. * Execute a function that is physics-plugin specific.
  67763. * @param {Function} func the function that will be executed.
  67764. * It accepts two parameters: the physics world and the physics joint.
  67765. */
  67766. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  67767. func(this._physicsPlugin.world, this._physicsJoint);
  67768. };
  67769. //TODO check if the native joints are the same
  67770. //Joint Types
  67771. PhysicsJoint.DistanceJoint = 0;
  67772. PhysicsJoint.HingeJoint = 1;
  67773. PhysicsJoint.BallAndSocketJoint = 2;
  67774. PhysicsJoint.WheelJoint = 3;
  67775. PhysicsJoint.SliderJoint = 4;
  67776. //OIMO
  67777. PhysicsJoint.PrismaticJoint = 5;
  67778. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  67779. PhysicsJoint.UniversalJoint = 6;
  67780. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  67781. //Cannon
  67782. //Similar to a Ball-Joint. Different in params
  67783. PhysicsJoint.PointToPointJoint = 8;
  67784. //Cannon only at the moment
  67785. PhysicsJoint.SpringJoint = 9;
  67786. PhysicsJoint.LockJoint = 10;
  67787. return PhysicsJoint;
  67788. }());
  67789. BABYLON.PhysicsJoint = PhysicsJoint;
  67790. /**
  67791. * A class representing a physics distance joint.
  67792. */
  67793. var DistanceJoint = /** @class */ (function (_super) {
  67794. __extends(DistanceJoint, _super);
  67795. function DistanceJoint(jointData) {
  67796. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  67797. }
  67798. /**
  67799. * Update the predefined distance.
  67800. */
  67801. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  67802. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  67803. };
  67804. return DistanceJoint;
  67805. }(PhysicsJoint));
  67806. BABYLON.DistanceJoint = DistanceJoint;
  67807. var MotorEnabledJoint = /** @class */ (function (_super) {
  67808. __extends(MotorEnabledJoint, _super);
  67809. function MotorEnabledJoint(type, jointData) {
  67810. return _super.call(this, type, jointData) || this;
  67811. }
  67812. /**
  67813. * Set the motor values.
  67814. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67815. * @param {number} force the force to apply
  67816. * @param {number} maxForce max force for this motor.
  67817. */
  67818. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  67819. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  67820. };
  67821. /**
  67822. * Set the motor's limits.
  67823. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67824. */
  67825. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  67826. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  67827. };
  67828. return MotorEnabledJoint;
  67829. }(PhysicsJoint));
  67830. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  67831. /**
  67832. * This class represents a single hinge physics joint
  67833. */
  67834. var HingeJoint = /** @class */ (function (_super) {
  67835. __extends(HingeJoint, _super);
  67836. function HingeJoint(jointData) {
  67837. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  67838. }
  67839. /**
  67840. * Set the motor values.
  67841. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67842. * @param {number} force the force to apply
  67843. * @param {number} maxForce max force for this motor.
  67844. */
  67845. HingeJoint.prototype.setMotor = function (force, maxForce) {
  67846. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  67847. };
  67848. /**
  67849. * Set the motor's limits.
  67850. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67851. */
  67852. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  67853. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  67854. };
  67855. return HingeJoint;
  67856. }(MotorEnabledJoint));
  67857. BABYLON.HingeJoint = HingeJoint;
  67858. /**
  67859. * This class represents a dual hinge physics joint (same as wheel joint)
  67860. */
  67861. var Hinge2Joint = /** @class */ (function (_super) {
  67862. __extends(Hinge2Joint, _super);
  67863. function Hinge2Joint(jointData) {
  67864. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  67865. }
  67866. /**
  67867. * Set the motor values.
  67868. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67869. * @param {number} force the force to apply
  67870. * @param {number} maxForce max force for this motor.
  67871. * @param {motorIndex} the motor's index, 0 or 1.
  67872. */
  67873. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  67874. if (motorIndex === void 0) { motorIndex = 0; }
  67875. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  67876. };
  67877. /**
  67878. * Set the motor limits.
  67879. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67880. * @param {number} upperLimit the upper limit
  67881. * @param {number} lowerLimit lower limit
  67882. * @param {motorIndex} the motor's index, 0 or 1.
  67883. */
  67884. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  67885. if (motorIndex === void 0) { motorIndex = 0; }
  67886. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  67887. };
  67888. return Hinge2Joint;
  67889. }(MotorEnabledJoint));
  67890. BABYLON.Hinge2Joint = Hinge2Joint;
  67891. })(BABYLON || (BABYLON = {}));
  67892. //# sourceMappingURL=babylon.physicsJoint.js.map
  67893. var BABYLON;
  67894. (function (BABYLON) {
  67895. var PhysicsImpostor = /** @class */ (function () {
  67896. function PhysicsImpostor(object, type, _options, _scene) {
  67897. if (_options === void 0) { _options = { mass: 0 }; }
  67898. var _this = this;
  67899. this.object = object;
  67900. this.type = type;
  67901. this._options = _options;
  67902. this._scene = _scene;
  67903. this._bodyUpdateRequired = false;
  67904. this._onBeforePhysicsStepCallbacks = new Array();
  67905. this._onAfterPhysicsStepCallbacks = new Array();
  67906. this._onPhysicsCollideCallbacks = [];
  67907. this._deltaPosition = BABYLON.Vector3.Zero();
  67908. this._isDisposed = false;
  67909. //temp variables for parent rotation calculations
  67910. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  67911. this._tmpQuat = new BABYLON.Quaternion();
  67912. this._tmpQuat2 = new BABYLON.Quaternion();
  67913. /**
  67914. * this function is executed by the physics engine.
  67915. */
  67916. this.beforeStep = function () {
  67917. if (!_this._physicsEngine) {
  67918. return;
  67919. }
  67920. _this.object.translate(_this._deltaPosition, -1);
  67921. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  67922. _this.object.computeWorldMatrix(false);
  67923. if (_this.object.parent && _this.object.rotationQuaternion) {
  67924. _this.getParentsRotation();
  67925. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  67926. }
  67927. else {
  67928. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  67929. }
  67930. if (!_this._options.disableBidirectionalTransformation) {
  67931. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  67932. }
  67933. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  67934. func(_this);
  67935. });
  67936. };
  67937. /**
  67938. * this function is executed by the physics engine.
  67939. */
  67940. this.afterStep = function () {
  67941. if (!_this._physicsEngine) {
  67942. return;
  67943. }
  67944. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  67945. func(_this);
  67946. });
  67947. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  67948. // object has now its world rotation. needs to be converted to local.
  67949. if (_this.object.parent && _this.object.rotationQuaternion) {
  67950. _this.getParentsRotation();
  67951. _this._tmpQuat.conjugateInPlace();
  67952. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  67953. }
  67954. // take the position set and make it the absolute position of this object.
  67955. _this.object.setAbsolutePosition(_this.object.position);
  67956. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  67957. _this.object.translate(_this._deltaPosition, 1);
  67958. };
  67959. /**
  67960. * Legacy collision detection event support
  67961. */
  67962. this.onCollideEvent = null;
  67963. //event and body object due to cannon's event-based architecture.
  67964. this.onCollide = function (e) {
  67965. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  67966. return;
  67967. }
  67968. if (!_this._physicsEngine) {
  67969. return;
  67970. }
  67971. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  67972. if (otherImpostor) {
  67973. // Legacy collision detection event support
  67974. if (_this.onCollideEvent) {
  67975. _this.onCollideEvent(_this, otherImpostor);
  67976. }
  67977. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  67978. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  67979. }).forEach(function (obj) {
  67980. obj.callback(_this, otherImpostor);
  67981. });
  67982. }
  67983. };
  67984. //sanity check!
  67985. if (!this.object) {
  67986. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  67987. return;
  67988. }
  67989. //legacy support for old syntax.
  67990. if (!this._scene && object.getScene) {
  67991. this._scene = object.getScene();
  67992. }
  67993. if (!this._scene) {
  67994. return;
  67995. }
  67996. this._physicsEngine = this._scene.getPhysicsEngine();
  67997. if (!this._physicsEngine) {
  67998. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  67999. }
  68000. else {
  68001. //set the object's quaternion, if not set
  68002. if (!this.object.rotationQuaternion) {
  68003. if (this.object.rotation) {
  68004. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  68005. }
  68006. else {
  68007. this.object.rotationQuaternion = new BABYLON.Quaternion();
  68008. }
  68009. }
  68010. //default options params
  68011. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  68012. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  68013. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  68014. this._joints = [];
  68015. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  68016. if (!this.object.parent || this._options.ignoreParent) {
  68017. this._init();
  68018. }
  68019. else if (this.object.parent.physicsImpostor) {
  68020. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  68021. }
  68022. }
  68023. }
  68024. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  68025. get: function () {
  68026. return this._isDisposed;
  68027. },
  68028. enumerable: true,
  68029. configurable: true
  68030. });
  68031. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  68032. get: function () {
  68033. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  68034. },
  68035. set: function (value) {
  68036. this.setMass(value);
  68037. },
  68038. enumerable: true,
  68039. configurable: true
  68040. });
  68041. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  68042. get: function () {
  68043. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  68044. },
  68045. set: function (value) {
  68046. if (!this._physicsEngine) {
  68047. return;
  68048. }
  68049. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  68050. },
  68051. enumerable: true,
  68052. configurable: true
  68053. });
  68054. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  68055. get: function () {
  68056. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  68057. },
  68058. set: function (value) {
  68059. if (!this._physicsEngine) {
  68060. return;
  68061. }
  68062. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  68063. },
  68064. enumerable: true,
  68065. configurable: true
  68066. });
  68067. /**
  68068. * This function will completly initialize this impostor.
  68069. * It will create a new body - but only if this mesh has no parent.
  68070. * If it has, this impostor will not be used other than to define the impostor
  68071. * of the child mesh.
  68072. */
  68073. PhysicsImpostor.prototype._init = function () {
  68074. if (!this._physicsEngine) {
  68075. return;
  68076. }
  68077. this._physicsEngine.removeImpostor(this);
  68078. this.physicsBody = null;
  68079. this._parent = this._parent || this._getPhysicsParent();
  68080. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  68081. this._physicsEngine.addImpostor(this);
  68082. }
  68083. };
  68084. PhysicsImpostor.prototype._getPhysicsParent = function () {
  68085. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  68086. var parentMesh = this.object.parent;
  68087. return parentMesh.physicsImpostor;
  68088. }
  68089. return null;
  68090. };
  68091. /**
  68092. * Should a new body be generated.
  68093. */
  68094. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  68095. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  68096. };
  68097. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  68098. this.forceUpdate();
  68099. };
  68100. /**
  68101. * Force a regeneration of this or the parent's impostor's body.
  68102. * Use under cautious - This will remove all joints already implemented.
  68103. */
  68104. PhysicsImpostor.prototype.forceUpdate = function () {
  68105. this._init();
  68106. if (this.parent && !this._options.ignoreParent) {
  68107. this.parent.forceUpdate();
  68108. }
  68109. };
  68110. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  68111. /*public get mesh(): AbstractMesh {
  68112. return this._mesh;
  68113. }*/
  68114. /**
  68115. * Gets the body that holds this impostor. Either its own, or its parent.
  68116. */
  68117. get: function () {
  68118. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  68119. },
  68120. /**
  68121. * Set the physics body. Used mainly by the physics engine/plugin
  68122. */
  68123. set: function (physicsBody) {
  68124. if (this._physicsBody && this._physicsEngine) {
  68125. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  68126. }
  68127. this._physicsBody = physicsBody;
  68128. this.resetUpdateFlags();
  68129. },
  68130. enumerable: true,
  68131. configurable: true
  68132. });
  68133. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  68134. get: function () {
  68135. return !this._options.ignoreParent && this._parent ? this._parent : null;
  68136. },
  68137. set: function (value) {
  68138. this._parent = value;
  68139. },
  68140. enumerable: true,
  68141. configurable: true
  68142. });
  68143. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  68144. this._bodyUpdateRequired = false;
  68145. };
  68146. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  68147. if (this.object.getBoundingInfo) {
  68148. var q = this.object.rotationQuaternion;
  68149. //reset rotation
  68150. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  68151. //calculate the world matrix with no rotation
  68152. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  68153. var boundingInfo = this.object.getBoundingInfo();
  68154. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  68155. //bring back the rotation
  68156. this.object.rotationQuaternion = q;
  68157. //calculate the world matrix with the new rotation
  68158. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  68159. return size;
  68160. }
  68161. else {
  68162. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  68163. }
  68164. };
  68165. PhysicsImpostor.prototype.getObjectCenter = function () {
  68166. if (this.object.getBoundingInfo) {
  68167. var boundingInfo = this.object.getBoundingInfo();
  68168. return boundingInfo.boundingBox.centerWorld;
  68169. }
  68170. else {
  68171. return this.object.position;
  68172. }
  68173. };
  68174. /**
  68175. * Get a specific parametes from the options parameter.
  68176. */
  68177. PhysicsImpostor.prototype.getParam = function (paramName) {
  68178. return this._options[paramName];
  68179. };
  68180. /**
  68181. * Sets a specific parameter in the options given to the physics plugin
  68182. */
  68183. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  68184. this._options[paramName] = value;
  68185. this._bodyUpdateRequired = true;
  68186. };
  68187. /**
  68188. * Specifically change the body's mass option. Won't recreate the physics body object
  68189. */
  68190. PhysicsImpostor.prototype.setMass = function (mass) {
  68191. if (this.getParam("mass") !== mass) {
  68192. this.setParam("mass", mass);
  68193. }
  68194. if (this._physicsEngine) {
  68195. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  68196. }
  68197. };
  68198. PhysicsImpostor.prototype.getLinearVelocity = function () {
  68199. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  68200. };
  68201. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  68202. if (this._physicsEngine) {
  68203. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  68204. }
  68205. };
  68206. PhysicsImpostor.prototype.getAngularVelocity = function () {
  68207. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  68208. };
  68209. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  68210. if (this._physicsEngine) {
  68211. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  68212. }
  68213. };
  68214. /**
  68215. * Execute a function with the physics plugin native code.
  68216. * Provide a function the will have two variables - the world object and the physics body object.
  68217. */
  68218. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  68219. if (this._physicsEngine) {
  68220. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  68221. }
  68222. };
  68223. /**
  68224. * Register a function that will be executed before the physics world is stepping forward.
  68225. */
  68226. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  68227. this._onBeforePhysicsStepCallbacks.push(func);
  68228. };
  68229. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  68230. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  68231. if (index > -1) {
  68232. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  68233. }
  68234. else {
  68235. BABYLON.Tools.Warn("Function to remove was not found");
  68236. }
  68237. };
  68238. /**
  68239. * Register a function that will be executed after the physics step
  68240. */
  68241. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  68242. this._onAfterPhysicsStepCallbacks.push(func);
  68243. };
  68244. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  68245. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  68246. if (index > -1) {
  68247. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  68248. }
  68249. else {
  68250. BABYLON.Tools.Warn("Function to remove was not found");
  68251. }
  68252. };
  68253. /**
  68254. * register a function that will be executed when this impostor collides against a different body.
  68255. */
  68256. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  68257. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  68258. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  68259. };
  68260. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  68261. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  68262. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  68263. if (index > -1) {
  68264. this._onPhysicsCollideCallbacks.splice(index, 1);
  68265. }
  68266. else {
  68267. BABYLON.Tools.Warn("Function to remove was not found");
  68268. }
  68269. };
  68270. PhysicsImpostor.prototype.getParentsRotation = function () {
  68271. var parent = this.object.parent;
  68272. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  68273. while (parent) {
  68274. if (parent.rotationQuaternion) {
  68275. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  68276. }
  68277. else {
  68278. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  68279. }
  68280. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  68281. parent = parent.parent;
  68282. }
  68283. return this._tmpQuat;
  68284. };
  68285. /**
  68286. * Apply a force
  68287. */
  68288. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  68289. if (this._physicsEngine) {
  68290. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  68291. }
  68292. return this;
  68293. };
  68294. /**
  68295. * Apply an impulse
  68296. */
  68297. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  68298. if (this._physicsEngine) {
  68299. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  68300. }
  68301. return this;
  68302. };
  68303. /**
  68304. * A help function to create a joint.
  68305. */
  68306. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  68307. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  68308. this.addJoint(otherImpostor, joint);
  68309. return this;
  68310. };
  68311. /**
  68312. * Add a joint to this impostor with a different impostor.
  68313. */
  68314. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  68315. this._joints.push({
  68316. otherImpostor: otherImpostor,
  68317. joint: joint
  68318. });
  68319. if (this._physicsEngine) {
  68320. this._physicsEngine.addJoint(this, otherImpostor, joint);
  68321. }
  68322. return this;
  68323. };
  68324. /**
  68325. * Will keep this body still, in a sleep mode.
  68326. */
  68327. PhysicsImpostor.prototype.sleep = function () {
  68328. if (this._physicsEngine) {
  68329. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  68330. }
  68331. return this;
  68332. };
  68333. /**
  68334. * Wake the body up.
  68335. */
  68336. PhysicsImpostor.prototype.wakeUp = function () {
  68337. if (this._physicsEngine) {
  68338. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  68339. }
  68340. return this;
  68341. };
  68342. PhysicsImpostor.prototype.clone = function (newObject) {
  68343. if (!newObject)
  68344. return null;
  68345. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  68346. };
  68347. PhysicsImpostor.prototype.dispose = function () {
  68348. var _this = this;
  68349. //no dispose if no physics engine is available.
  68350. if (!this._physicsEngine) {
  68351. return;
  68352. }
  68353. this._joints.forEach(function (j) {
  68354. if (_this._physicsEngine) {
  68355. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  68356. }
  68357. });
  68358. //dispose the physics body
  68359. this._physicsEngine.removeImpostor(this);
  68360. if (this.parent) {
  68361. this.parent.forceUpdate();
  68362. }
  68363. else {
  68364. /*this._object.getChildMeshes().forEach(function(mesh) {
  68365. if (mesh.physicsImpostor) {
  68366. if (disposeChildren) {
  68367. mesh.physicsImpostor.dispose();
  68368. mesh.physicsImpostor = null;
  68369. }
  68370. }
  68371. })*/
  68372. }
  68373. this._isDisposed = true;
  68374. };
  68375. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  68376. this._deltaPosition.copyFrom(position);
  68377. };
  68378. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  68379. if (!this._deltaRotation) {
  68380. this._deltaRotation = new BABYLON.Quaternion();
  68381. }
  68382. this._deltaRotation.copyFrom(rotation);
  68383. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  68384. };
  68385. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  68386. if (this._physicsEngine) {
  68387. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  68388. }
  68389. return this;
  68390. };
  68391. PhysicsImpostor.prototype.getRadius = function () {
  68392. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  68393. };
  68394. /**
  68395. * Sync a bone with this impostor
  68396. * @param bone The bone to sync to the impostor.
  68397. * @param boneMesh The mesh that the bone is influencing.
  68398. * @param jointPivot The pivot of the joint / bone in local space.
  68399. * @param distToJoint Optional distance from the impostor to the joint.
  68400. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  68401. */
  68402. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  68403. var tempVec = PhysicsImpostor._tmpVecs[0];
  68404. var mesh = this.object;
  68405. if (mesh.rotationQuaternion) {
  68406. if (adjustRotation) {
  68407. var tempQuat = PhysicsImpostor._tmpQuat;
  68408. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  68409. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  68410. }
  68411. else {
  68412. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  68413. }
  68414. }
  68415. tempVec.x = 0;
  68416. tempVec.y = 0;
  68417. tempVec.z = 0;
  68418. if (jointPivot) {
  68419. tempVec.x = jointPivot.x;
  68420. tempVec.y = jointPivot.y;
  68421. tempVec.z = jointPivot.z;
  68422. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  68423. if (distToJoint === undefined || distToJoint === null) {
  68424. distToJoint = jointPivot.length();
  68425. }
  68426. tempVec.x *= distToJoint;
  68427. tempVec.y *= distToJoint;
  68428. tempVec.z *= distToJoint;
  68429. }
  68430. if (bone.getParent()) {
  68431. tempVec.addInPlace(mesh.getAbsolutePosition());
  68432. bone.setAbsolutePosition(tempVec, boneMesh);
  68433. }
  68434. else {
  68435. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  68436. boneMesh.position.x -= tempVec.x;
  68437. boneMesh.position.y -= tempVec.y;
  68438. boneMesh.position.z -= tempVec.z;
  68439. }
  68440. };
  68441. /**
  68442. * Sync impostor to a bone
  68443. * @param bone The bone that the impostor will be synced to.
  68444. * @param boneMesh The mesh that the bone is influencing.
  68445. * @param jointPivot The pivot of the joint / bone in local space.
  68446. * @param distToJoint Optional distance from the impostor to the joint.
  68447. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  68448. * @param boneAxis Optional vector3 axis the bone is aligned with
  68449. */
  68450. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  68451. var mesh = this.object;
  68452. if (mesh.rotationQuaternion) {
  68453. if (adjustRotation) {
  68454. var tempQuat = PhysicsImpostor._tmpQuat;
  68455. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  68456. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  68457. }
  68458. else {
  68459. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  68460. }
  68461. }
  68462. var pos = PhysicsImpostor._tmpVecs[0];
  68463. var boneDir = PhysicsImpostor._tmpVecs[1];
  68464. if (!boneAxis) {
  68465. boneAxis = PhysicsImpostor._tmpVecs[2];
  68466. boneAxis.x = 0;
  68467. boneAxis.y = 1;
  68468. boneAxis.z = 0;
  68469. }
  68470. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  68471. bone.getAbsolutePositionToRef(boneMesh, pos);
  68472. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  68473. distToJoint = jointPivot.length();
  68474. }
  68475. if (distToJoint !== undefined && distToJoint !== null) {
  68476. pos.x += boneDir.x * distToJoint;
  68477. pos.y += boneDir.y * distToJoint;
  68478. pos.z += boneDir.z * distToJoint;
  68479. }
  68480. mesh.setAbsolutePosition(pos);
  68481. };
  68482. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  68483. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  68484. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68485. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  68486. //Impostor types
  68487. PhysicsImpostor.NoImpostor = 0;
  68488. PhysicsImpostor.SphereImpostor = 1;
  68489. PhysicsImpostor.BoxImpostor = 2;
  68490. PhysicsImpostor.PlaneImpostor = 3;
  68491. PhysicsImpostor.MeshImpostor = 4;
  68492. PhysicsImpostor.CylinderImpostor = 7;
  68493. PhysicsImpostor.ParticleImpostor = 8;
  68494. PhysicsImpostor.HeightmapImpostor = 9;
  68495. return PhysicsImpostor;
  68496. }());
  68497. BABYLON.PhysicsImpostor = PhysicsImpostor;
  68498. })(BABYLON || (BABYLON = {}));
  68499. //# sourceMappingURL=babylon.physicsImpostor.js.map
  68500. var BABYLON;
  68501. (function (BABYLON) {
  68502. var PhysicsEngine = /** @class */ (function () {
  68503. function PhysicsEngine(gravity, _physicsPlugin) {
  68504. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  68505. this._physicsPlugin = _physicsPlugin;
  68506. //new methods and parameters
  68507. this._impostors = [];
  68508. this._joints = [];
  68509. if (!this._physicsPlugin.isSupported()) {
  68510. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  68511. + "Please make sure it is included.");
  68512. }
  68513. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  68514. this.setGravity(gravity);
  68515. this.setTimeStep();
  68516. }
  68517. PhysicsEngine.prototype.setGravity = function (gravity) {
  68518. this.gravity = gravity;
  68519. this._physicsPlugin.setGravity(this.gravity);
  68520. };
  68521. /**
  68522. * Set the time step of the physics engine.
  68523. * default is 1/60.
  68524. * To slow it down, enter 1/600 for example.
  68525. * To speed it up, 1/30
  68526. * @param {number} newTimeStep the new timestep to apply to this world.
  68527. */
  68528. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  68529. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  68530. this._physicsPlugin.setTimeStep(newTimeStep);
  68531. };
  68532. /**
  68533. * Get the time step of the physics engine.
  68534. */
  68535. PhysicsEngine.prototype.getTimeStep = function () {
  68536. return this._physicsPlugin.getTimeStep();
  68537. };
  68538. PhysicsEngine.prototype.dispose = function () {
  68539. this._impostors.forEach(function (impostor) {
  68540. impostor.dispose();
  68541. });
  68542. this._physicsPlugin.dispose();
  68543. };
  68544. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  68545. return this._physicsPlugin.name;
  68546. };
  68547. /**
  68548. * Adding a new impostor for the impostor tracking.
  68549. * This will be done by the impostor itself.
  68550. * @param {PhysicsImpostor} impostor the impostor to add
  68551. */
  68552. PhysicsEngine.prototype.addImpostor = function (impostor) {
  68553. impostor.uniqueId = this._impostors.push(impostor);
  68554. //if no parent, generate the body
  68555. if (!impostor.parent) {
  68556. this._physicsPlugin.generatePhysicsBody(impostor);
  68557. }
  68558. };
  68559. /**
  68560. * Remove an impostor from the engine.
  68561. * This impostor and its mesh will not longer be updated by the physics engine.
  68562. * @param {PhysicsImpostor} impostor the impostor to remove
  68563. */
  68564. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  68565. var index = this._impostors.indexOf(impostor);
  68566. if (index > -1) {
  68567. var removed = this._impostors.splice(index, 1);
  68568. //Is it needed?
  68569. if (removed.length) {
  68570. //this will also remove it from the world.
  68571. removed[0].physicsBody = null;
  68572. }
  68573. }
  68574. };
  68575. /**
  68576. * Add a joint to the physics engine
  68577. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  68578. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  68579. * @param {PhysicsJoint} the joint that will connect both impostors.
  68580. */
  68581. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  68582. var impostorJoint = {
  68583. mainImpostor: mainImpostor,
  68584. connectedImpostor: connectedImpostor,
  68585. joint: joint
  68586. };
  68587. joint.physicsPlugin = this._physicsPlugin;
  68588. this._joints.push(impostorJoint);
  68589. this._physicsPlugin.generateJoint(impostorJoint);
  68590. };
  68591. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  68592. var matchingJoints = this._joints.filter(function (impostorJoint) {
  68593. return (impostorJoint.connectedImpostor === connectedImpostor
  68594. && impostorJoint.joint === joint
  68595. && impostorJoint.mainImpostor === mainImpostor);
  68596. });
  68597. if (matchingJoints.length) {
  68598. this._physicsPlugin.removeJoint(matchingJoints[0]);
  68599. //TODO remove it from the list as well
  68600. }
  68601. };
  68602. /**
  68603. * Called by the scene. no need to call it.
  68604. */
  68605. PhysicsEngine.prototype._step = function (delta) {
  68606. var _this = this;
  68607. //check if any mesh has no body / requires an update
  68608. this._impostors.forEach(function (impostor) {
  68609. if (impostor.isBodyInitRequired()) {
  68610. _this._physicsPlugin.generatePhysicsBody(impostor);
  68611. }
  68612. });
  68613. if (delta > 0.1) {
  68614. delta = 0.1;
  68615. }
  68616. else if (delta <= 0) {
  68617. delta = 1.0 / 60.0;
  68618. }
  68619. this._physicsPlugin.executeStep(delta, this._impostors);
  68620. };
  68621. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  68622. return this._physicsPlugin;
  68623. };
  68624. PhysicsEngine.prototype.getImpostors = function () {
  68625. return this._impostors;
  68626. };
  68627. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  68628. for (var i = 0; i < this._impostors.length; ++i) {
  68629. if (this._impostors[i].object === object) {
  68630. return this._impostors[i];
  68631. }
  68632. }
  68633. return null;
  68634. };
  68635. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  68636. for (var i = 0; i < this._impostors.length; ++i) {
  68637. if (this._impostors[i].physicsBody === body) {
  68638. return this._impostors[i];
  68639. }
  68640. }
  68641. return null;
  68642. };
  68643. // Statics
  68644. PhysicsEngine.Epsilon = 0.001;
  68645. return PhysicsEngine;
  68646. }());
  68647. BABYLON.PhysicsEngine = PhysicsEngine;
  68648. })(BABYLON || (BABYLON = {}));
  68649. //# sourceMappingURL=babylon.physicsEngine.js.map
  68650. var BABYLON;
  68651. (function (BABYLON) {
  68652. var PhysicsHelper = /** @class */ (function () {
  68653. function PhysicsHelper(scene) {
  68654. this._scene = scene;
  68655. this._physicsEngine = this._scene.getPhysicsEngine();
  68656. if (!this._physicsEngine) {
  68657. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  68658. }
  68659. }
  68660. /**
  68661. * @param {Vector3} origin the origin of the explosion
  68662. * @param {number} radius the explosion radius
  68663. * @param {number} strength the explosion strength
  68664. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68665. */
  68666. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  68667. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68668. if (!this._physicsEngine) {
  68669. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  68670. return null;
  68671. }
  68672. var impostors = this._physicsEngine.getImpostors();
  68673. if (impostors.length === 0) {
  68674. return null;
  68675. }
  68676. var event = new PhysicsRadialExplosionEvent(this._scene);
  68677. impostors.forEach(function (impostor) {
  68678. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68679. if (!impostorForceAndContactPoint) {
  68680. return;
  68681. }
  68682. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68683. });
  68684. event.dispose(false);
  68685. return event;
  68686. };
  68687. /**
  68688. * @param {Vector3} origin the origin of the explosion
  68689. * @param {number} radius the explosion radius
  68690. * @param {number} strength the explosion strength
  68691. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68692. */
  68693. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  68694. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68695. if (!this._physicsEngine) {
  68696. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68697. return null;
  68698. }
  68699. var impostors = this._physicsEngine.getImpostors();
  68700. if (impostors.length === 0) {
  68701. return null;
  68702. }
  68703. var event = new PhysicsRadialExplosionEvent(this._scene);
  68704. impostors.forEach(function (impostor) {
  68705. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68706. if (!impostorForceAndContactPoint) {
  68707. return;
  68708. }
  68709. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68710. });
  68711. event.dispose(false);
  68712. return event;
  68713. };
  68714. /**
  68715. * @param {Vector3} origin the origin of the explosion
  68716. * @param {number} radius the explosion radius
  68717. * @param {number} strength the explosion strength
  68718. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68719. */
  68720. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  68721. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68722. if (!this._physicsEngine) {
  68723. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68724. return null;
  68725. }
  68726. var impostors = this._physicsEngine.getImpostors();
  68727. if (impostors.length === 0) {
  68728. return null;
  68729. }
  68730. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  68731. event.dispose(false);
  68732. return event;
  68733. };
  68734. /**
  68735. * @param {Vector3} origin the origin of the updraft
  68736. * @param {number} radius the radius of the updraft
  68737. * @param {number} strength the strength of the updraft
  68738. * @param {number} height the height of the updraft
  68739. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  68740. */
  68741. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  68742. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  68743. if (!this._physicsEngine) {
  68744. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68745. return null;
  68746. }
  68747. if (this._physicsEngine.getImpostors().length === 0) {
  68748. return null;
  68749. }
  68750. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  68751. event.dispose(false);
  68752. return event;
  68753. };
  68754. /**
  68755. * @param {Vector3} origin the of the vortex
  68756. * @param {number} radius the radius of the vortex
  68757. * @param {number} strength the strength of the vortex
  68758. * @param {number} height the height of the vortex
  68759. */
  68760. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  68761. if (!this._physicsEngine) {
  68762. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68763. return null;
  68764. }
  68765. if (this._physicsEngine.getImpostors().length === 0) {
  68766. return null;
  68767. }
  68768. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  68769. event.dispose(false);
  68770. return event;
  68771. };
  68772. return PhysicsHelper;
  68773. }());
  68774. BABYLON.PhysicsHelper = PhysicsHelper;
  68775. /***** Radial explosion *****/
  68776. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  68777. function PhysicsRadialExplosionEvent(scene) {
  68778. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  68779. this._rays = [];
  68780. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  68781. this._scene = scene;
  68782. }
  68783. /**
  68784. * Returns the data related to the radial explosion event (sphere & rays).
  68785. * @returns {PhysicsRadialExplosionEventData}
  68786. */
  68787. PhysicsRadialExplosionEvent.prototype.getData = function () {
  68788. this._dataFetched = true;
  68789. return {
  68790. sphere: this._sphere,
  68791. rays: this._rays,
  68792. };
  68793. };
  68794. /**
  68795. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  68796. * @param impostor
  68797. * @param {Vector3} origin the origin of the explosion
  68798. * @param {number} radius the explosion radius
  68799. * @param {number} strength the explosion strength
  68800. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  68801. * @returns {Nullable<PhysicsForceAndContactPoint>}
  68802. */
  68803. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  68804. if (impostor.mass === 0) {
  68805. return null;
  68806. }
  68807. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  68808. return null;
  68809. }
  68810. if (impostor.object.getClassName() !== 'Mesh') {
  68811. return null;
  68812. }
  68813. var impostorObject = impostor.object;
  68814. var impostorObjectCenter = impostor.getObjectCenter();
  68815. var direction = impostorObjectCenter.subtract(origin);
  68816. var ray = new BABYLON.Ray(origin, direction, radius);
  68817. this._rays.push(ray);
  68818. var hit = ray.intersectsMesh(impostorObject);
  68819. var contactPoint = hit.pickedPoint;
  68820. if (!contactPoint) {
  68821. return null;
  68822. }
  68823. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  68824. if (distanceFromOrigin > radius) {
  68825. return null;
  68826. }
  68827. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  68828. ? strength
  68829. : strength * (1 - (distanceFromOrigin / radius));
  68830. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  68831. return { force: force, contactPoint: contactPoint };
  68832. };
  68833. /**
  68834. * Disposes the sphere.
  68835. * @param {bolean} force
  68836. */
  68837. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  68838. var _this = this;
  68839. if (force === void 0) { force = true; }
  68840. if (force) {
  68841. this._sphere.dispose();
  68842. }
  68843. else {
  68844. setTimeout(function () {
  68845. if (!_this._dataFetched) {
  68846. _this._sphere.dispose();
  68847. }
  68848. }, 0);
  68849. }
  68850. };
  68851. /*** Helpers ***/
  68852. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  68853. if (!this._sphere) {
  68854. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  68855. this._sphere.isVisible = false;
  68856. }
  68857. };
  68858. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  68859. var impostorObject = impostor.object;
  68860. this._prepareSphere();
  68861. this._sphere.position = origin;
  68862. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  68863. this._sphere._updateBoundingInfo();
  68864. this._sphere.computeWorldMatrix(true);
  68865. return this._sphere.intersectsMesh(impostorObject, true);
  68866. };
  68867. return PhysicsRadialExplosionEvent;
  68868. }());
  68869. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  68870. /***** Gravitational Field *****/
  68871. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  68872. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  68873. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68874. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68875. this._physicsHelper = physicsHelper;
  68876. this._scene = scene;
  68877. this._origin = origin;
  68878. this._radius = radius;
  68879. this._strength = strength;
  68880. this._falloff = falloff;
  68881. this._tickCallback = this._tick.bind(this);
  68882. }
  68883. /**
  68884. * Returns the data related to the gravitational field event (sphere).
  68885. * @returns {PhysicsGravitationalFieldEventData}
  68886. */
  68887. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  68888. this._dataFetched = true;
  68889. return {
  68890. sphere: this._sphere,
  68891. };
  68892. };
  68893. /**
  68894. * Enables the gravitational field.
  68895. */
  68896. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  68897. this._tickCallback.call(this);
  68898. this._scene.registerBeforeRender(this._tickCallback);
  68899. };
  68900. /**
  68901. * Disables the gravitational field.
  68902. */
  68903. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  68904. this._scene.unregisterBeforeRender(this._tickCallback);
  68905. };
  68906. /**
  68907. * Disposes the sphere.
  68908. * @param {bolean} force
  68909. */
  68910. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  68911. var _this = this;
  68912. if (force === void 0) { force = true; }
  68913. if (force) {
  68914. this._sphere.dispose();
  68915. }
  68916. else {
  68917. setTimeout(function () {
  68918. if (!_this._dataFetched) {
  68919. _this._sphere.dispose();
  68920. }
  68921. }, 0);
  68922. }
  68923. };
  68924. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  68925. // Since the params won't change, we fetch the event only once
  68926. if (this._sphere) {
  68927. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  68928. }
  68929. else {
  68930. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  68931. if (radialExplosionEvent) {
  68932. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  68933. }
  68934. }
  68935. };
  68936. return PhysicsGravitationalFieldEvent;
  68937. }());
  68938. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  68939. /***** Updraft *****/
  68940. var PhysicsUpdraftEvent = /** @class */ (function () {
  68941. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  68942. this._scene = _scene;
  68943. this._origin = _origin;
  68944. this._radius = _radius;
  68945. this._strength = _strength;
  68946. this._height = _height;
  68947. this._updraftMode = _updraftMode;
  68948. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  68949. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  68950. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  68951. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68952. this._physicsEngine = this._scene.getPhysicsEngine();
  68953. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  68954. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  68955. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  68956. this._originDirection = this._origin.subtract(this._originTop).normalize();
  68957. }
  68958. this._tickCallback = this._tick.bind(this);
  68959. }
  68960. /**
  68961. * Returns the data related to the updraft event (cylinder).
  68962. * @returns {PhysicsUpdraftEventData}
  68963. */
  68964. PhysicsUpdraftEvent.prototype.getData = function () {
  68965. this._dataFetched = true;
  68966. return {
  68967. cylinder: this._cylinder,
  68968. };
  68969. };
  68970. /**
  68971. * Enables the updraft.
  68972. */
  68973. PhysicsUpdraftEvent.prototype.enable = function () {
  68974. this._tickCallback.call(this);
  68975. this._scene.registerBeforeRender(this._tickCallback);
  68976. };
  68977. /**
  68978. * Disables the cortex.
  68979. */
  68980. PhysicsUpdraftEvent.prototype.disable = function () {
  68981. this._scene.unregisterBeforeRender(this._tickCallback);
  68982. };
  68983. /**
  68984. * Disposes the sphere.
  68985. * @param {bolean} force
  68986. */
  68987. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  68988. var _this = this;
  68989. if (force === void 0) { force = true; }
  68990. if (force) {
  68991. this._cylinder.dispose();
  68992. }
  68993. else {
  68994. setTimeout(function () {
  68995. if (!_this._dataFetched) {
  68996. _this._cylinder.dispose();
  68997. }
  68998. }, 0);
  68999. }
  69000. };
  69001. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  69002. if (impostor.mass === 0) {
  69003. return null;
  69004. }
  69005. if (!this._intersectsWithCylinder(impostor)) {
  69006. return null;
  69007. }
  69008. var impostorObjectCenter = impostor.getObjectCenter();
  69009. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  69010. var direction = this._originDirection;
  69011. }
  69012. else {
  69013. var direction = impostorObjectCenter.subtract(this._originTop);
  69014. }
  69015. var multiplier = this._strength * -1;
  69016. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  69017. return { force: force, contactPoint: impostorObjectCenter };
  69018. };
  69019. PhysicsUpdraftEvent.prototype._tick = function () {
  69020. var _this = this;
  69021. this._physicsEngine.getImpostors().forEach(function (impostor) {
  69022. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  69023. if (!impostorForceAndContactPoint) {
  69024. return;
  69025. }
  69026. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  69027. });
  69028. };
  69029. /*** Helpers ***/
  69030. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  69031. if (!this._cylinder) {
  69032. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  69033. height: this._height,
  69034. diameter: this._radius * 2,
  69035. }, this._scene);
  69036. this._cylinder.isVisible = false;
  69037. }
  69038. };
  69039. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  69040. var impostorObject = impostor.object;
  69041. this._prepareCylinder();
  69042. this._cylinder.position = this._cylinderPosition;
  69043. return this._cylinder.intersectsMesh(impostorObject, true);
  69044. };
  69045. return PhysicsUpdraftEvent;
  69046. }());
  69047. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  69048. /***** Vortex *****/
  69049. var PhysicsVortexEvent = /** @class */ (function () {
  69050. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  69051. this._scene = _scene;
  69052. this._origin = _origin;
  69053. this._radius = _radius;
  69054. this._strength = _strength;
  69055. this._height = _height;
  69056. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  69057. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  69058. this._updraftMultiplier = 0.02;
  69059. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  69060. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  69061. this._physicsEngine = this._scene.getPhysicsEngine();
  69062. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  69063. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  69064. this._tickCallback = this._tick.bind(this);
  69065. }
  69066. /**
  69067. * Returns the data related to the vortex event (cylinder).
  69068. * @returns {PhysicsVortexEventData}
  69069. */
  69070. PhysicsVortexEvent.prototype.getData = function () {
  69071. this._dataFetched = true;
  69072. return {
  69073. cylinder: this._cylinder,
  69074. };
  69075. };
  69076. /**
  69077. * Enables the vortex.
  69078. */
  69079. PhysicsVortexEvent.prototype.enable = function () {
  69080. this._tickCallback.call(this);
  69081. this._scene.registerBeforeRender(this._tickCallback);
  69082. };
  69083. /**
  69084. * Disables the cortex.
  69085. */
  69086. PhysicsVortexEvent.prototype.disable = function () {
  69087. this._scene.unregisterBeforeRender(this._tickCallback);
  69088. };
  69089. /**
  69090. * Disposes the sphere.
  69091. * @param {bolean} force
  69092. */
  69093. PhysicsVortexEvent.prototype.dispose = function (force) {
  69094. var _this = this;
  69095. if (force === void 0) { force = true; }
  69096. if (force) {
  69097. this._cylinder.dispose();
  69098. }
  69099. else {
  69100. setTimeout(function () {
  69101. if (!_this._dataFetched) {
  69102. _this._cylinder.dispose();
  69103. }
  69104. }, 0);
  69105. }
  69106. };
  69107. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  69108. if (impostor.mass === 0) {
  69109. return null;
  69110. }
  69111. if (!this._intersectsWithCylinder(impostor)) {
  69112. return null;
  69113. }
  69114. if (impostor.object.getClassName() !== 'Mesh') {
  69115. return null;
  69116. }
  69117. var impostorObject = impostor.object;
  69118. var impostorObjectCenter = impostor.getObjectCenter();
  69119. 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)
  69120. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  69121. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  69122. var hit = ray.intersectsMesh(impostorObject);
  69123. var contactPoint = hit.pickedPoint;
  69124. if (!contactPoint) {
  69125. return null;
  69126. }
  69127. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  69128. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  69129. var directionToOrigin = contactPoint.normalize();
  69130. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  69131. directionToOrigin = directionToOrigin.negate();
  69132. }
  69133. // TODO: find a more physically based solution
  69134. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  69135. var forceX = directionToOrigin.x * this._strength / 8;
  69136. var forceY = directionToOrigin.y * this._updraftMultiplier;
  69137. var forceZ = directionToOrigin.z * this._strength / 8;
  69138. }
  69139. else {
  69140. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  69141. var forceY = this._originTop.y * this._updraftMultiplier;
  69142. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  69143. }
  69144. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  69145. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  69146. return { force: force, contactPoint: impostorObjectCenter };
  69147. };
  69148. PhysicsVortexEvent.prototype._tick = function () {
  69149. var _this = this;
  69150. this._physicsEngine.getImpostors().forEach(function (impostor) {
  69151. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  69152. if (!impostorForceAndContactPoint) {
  69153. return;
  69154. }
  69155. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  69156. });
  69157. };
  69158. /*** Helpers ***/
  69159. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  69160. if (!this._cylinder) {
  69161. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  69162. height: this._height,
  69163. diameter: this._radius * 2,
  69164. }, this._scene);
  69165. this._cylinder.isVisible = false;
  69166. }
  69167. };
  69168. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  69169. var impostorObject = impostor.object;
  69170. this._prepareCylinder();
  69171. this._cylinder.position = this._cylinderPosition;
  69172. return this._cylinder.intersectsMesh(impostorObject, true);
  69173. };
  69174. return PhysicsVortexEvent;
  69175. }());
  69176. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  69177. /***** Enums *****/
  69178. /**
  69179. * The strenght of the force in correspondence to the distance of the affected object
  69180. */
  69181. var PhysicsRadialImpulseFalloff;
  69182. (function (PhysicsRadialImpulseFalloff) {
  69183. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  69184. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  69185. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  69186. /**
  69187. * The strenght of the force in correspondence to the distance of the affected object
  69188. */
  69189. var PhysicsUpdraftMode;
  69190. (function (PhysicsUpdraftMode) {
  69191. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  69192. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  69193. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  69194. })(BABYLON || (BABYLON = {}));
  69195. //# sourceMappingURL=babylon.physicsHelper.js.map
  69196. var BABYLON;
  69197. (function (BABYLON) {
  69198. var CannonJSPlugin = /** @class */ (function () {
  69199. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  69200. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  69201. if (iterations === void 0) { iterations = 10; }
  69202. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  69203. this.name = "CannonJSPlugin";
  69204. this._physicsMaterials = new Array();
  69205. this._fixedTimeStep = 1 / 60;
  69206. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  69207. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  69208. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  69209. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  69210. this._tmpPosition = BABYLON.Vector3.Zero();
  69211. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  69212. this._tmpUnityRotation = new BABYLON.Quaternion();
  69213. if (!this.isSupported()) {
  69214. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  69215. return;
  69216. }
  69217. this._extendNamespace();
  69218. this.world = new this.BJSCANNON.World();
  69219. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  69220. this.world.solver.iterations = iterations;
  69221. }
  69222. CannonJSPlugin.prototype.setGravity = function (gravity) {
  69223. this.world.gravity.copy(gravity);
  69224. };
  69225. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  69226. this._fixedTimeStep = timeStep;
  69227. };
  69228. CannonJSPlugin.prototype.getTimeStep = function () {
  69229. return this._fixedTimeStep;
  69230. };
  69231. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  69232. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  69233. };
  69234. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  69235. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  69236. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  69237. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  69238. };
  69239. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  69240. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  69241. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  69242. impostor.physicsBody.applyForce(impulse, worldPoint);
  69243. };
  69244. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  69245. //parent-child relationship. Does this impostor has a parent impostor?
  69246. if (impostor.parent) {
  69247. if (impostor.physicsBody) {
  69248. this.removePhysicsBody(impostor);
  69249. //TODO is that needed?
  69250. impostor.forceUpdate();
  69251. }
  69252. return;
  69253. }
  69254. //should a new body be created for this impostor?
  69255. if (impostor.isBodyInitRequired()) {
  69256. var shape = this._createShape(impostor);
  69257. //unregister events, if body is being changed
  69258. var oldBody = impostor.physicsBody;
  69259. if (oldBody) {
  69260. this.removePhysicsBody(impostor);
  69261. }
  69262. //create the body and material
  69263. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  69264. var bodyCreationObject = {
  69265. mass: impostor.getParam("mass"),
  69266. material: material
  69267. };
  69268. // A simple extend, in case native options were used.
  69269. var nativeOptions = impostor.getParam("nativeOptions");
  69270. for (var key in nativeOptions) {
  69271. if (nativeOptions.hasOwnProperty(key)) {
  69272. bodyCreationObject[key] = nativeOptions[key];
  69273. }
  69274. }
  69275. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  69276. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  69277. this.world.addEventListener("preStep", impostor.beforeStep);
  69278. this.world.addEventListener("postStep", impostor.afterStep);
  69279. impostor.physicsBody.addShape(shape);
  69280. this.world.add(impostor.physicsBody);
  69281. //try to keep the body moving in the right direction by taking old properties.
  69282. //Should be tested!
  69283. if (oldBody) {
  69284. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  69285. impostor.physicsBody[param].copy(oldBody[param]);
  69286. });
  69287. }
  69288. this._processChildMeshes(impostor);
  69289. }
  69290. //now update the body's transformation
  69291. this._updatePhysicsBodyTransformation(impostor);
  69292. };
  69293. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  69294. var _this = this;
  69295. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  69296. var currentRotation = mainImpostor.object.rotationQuaternion;
  69297. if (meshChildren.length) {
  69298. var processMesh = function (localPosition, mesh) {
  69299. if (!currentRotation || !mesh.rotationQuaternion) {
  69300. return;
  69301. }
  69302. var childImpostor = mesh.getPhysicsImpostor();
  69303. if (childImpostor) {
  69304. var parent = childImpostor.parent;
  69305. if (parent !== mainImpostor) {
  69306. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  69307. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  69308. if (childImpostor.physicsBody) {
  69309. _this.removePhysicsBody(childImpostor);
  69310. childImpostor.physicsBody = null;
  69311. }
  69312. childImpostor.parent = mainImpostor;
  69313. childImpostor.resetUpdateFlags();
  69314. 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));
  69315. //Add the mass of the children.
  69316. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  69317. }
  69318. }
  69319. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  69320. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  69321. };
  69322. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  69323. }
  69324. };
  69325. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  69326. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  69327. this.world.removeEventListener("preStep", impostor.beforeStep);
  69328. this.world.removeEventListener("postStep", impostor.afterStep);
  69329. this.world.remove(impostor.physicsBody);
  69330. };
  69331. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  69332. var mainBody = impostorJoint.mainImpostor.physicsBody;
  69333. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  69334. if (!mainBody || !connectedBody) {
  69335. return;
  69336. }
  69337. var constraint;
  69338. var jointData = impostorJoint.joint.jointData;
  69339. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  69340. var constraintData = {
  69341. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  69342. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  69343. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  69344. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  69345. maxForce: jointData.nativeParams.maxForce,
  69346. collideConnected: !!jointData.collision
  69347. };
  69348. switch (impostorJoint.joint.type) {
  69349. case BABYLON.PhysicsJoint.HingeJoint:
  69350. case BABYLON.PhysicsJoint.Hinge2Joint:
  69351. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  69352. break;
  69353. case BABYLON.PhysicsJoint.DistanceJoint:
  69354. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  69355. break;
  69356. case BABYLON.PhysicsJoint.SpringJoint:
  69357. var springData = jointData;
  69358. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  69359. restLength: springData.length,
  69360. stiffness: springData.stiffness,
  69361. damping: springData.damping,
  69362. localAnchorA: constraintData.pivotA,
  69363. localAnchorB: constraintData.pivotB
  69364. });
  69365. break;
  69366. case BABYLON.PhysicsJoint.LockJoint:
  69367. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  69368. break;
  69369. case BABYLON.PhysicsJoint.PointToPointJoint:
  69370. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  69371. default:
  69372. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  69373. break;
  69374. }
  69375. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  69376. constraint.collideConnected = !!jointData.collision;
  69377. impostorJoint.joint.physicsJoint = constraint;
  69378. //don't add spring as constraint, as it is not one.
  69379. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  69380. this.world.addConstraint(constraint);
  69381. }
  69382. else {
  69383. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  69384. constraint.applyForce();
  69385. });
  69386. }
  69387. };
  69388. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  69389. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  69390. };
  69391. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  69392. var index;
  69393. var mat;
  69394. for (index = 0; index < this._physicsMaterials.length; index++) {
  69395. mat = this._physicsMaterials[index];
  69396. if (mat.friction === friction && mat.restitution === restitution) {
  69397. return mat;
  69398. }
  69399. }
  69400. var currentMat = new this.BJSCANNON.Material(name);
  69401. currentMat.friction = friction;
  69402. currentMat.restitution = restitution;
  69403. this._physicsMaterials.push(currentMat);
  69404. return currentMat;
  69405. };
  69406. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  69407. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  69408. };
  69409. CannonJSPlugin.prototype._createShape = function (impostor) {
  69410. var object = impostor.object;
  69411. var returnValue;
  69412. var extendSize = impostor.getObjectExtendSize();
  69413. switch (impostor.type) {
  69414. case BABYLON.PhysicsImpostor.SphereImpostor:
  69415. var radiusX = extendSize.x;
  69416. var radiusY = extendSize.y;
  69417. var radiusZ = extendSize.z;
  69418. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  69419. break;
  69420. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  69421. case BABYLON.PhysicsImpostor.CylinderImpostor:
  69422. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  69423. break;
  69424. case BABYLON.PhysicsImpostor.BoxImpostor:
  69425. var box = extendSize.scale(0.5);
  69426. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  69427. break;
  69428. case BABYLON.PhysicsImpostor.PlaneImpostor:
  69429. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  69430. returnValue = new this.BJSCANNON.Plane();
  69431. break;
  69432. case BABYLON.PhysicsImpostor.MeshImpostor:
  69433. // should transform the vertex data to world coordinates!!
  69434. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  69435. var rawFaces = object.getIndices ? object.getIndices() : [];
  69436. if (!rawVerts)
  69437. return;
  69438. // get only scale! so the object could transform correctly.
  69439. var oldPosition = object.position.clone();
  69440. var oldRotation = object.rotation && object.rotation.clone();
  69441. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  69442. object.position.copyFromFloats(0, 0, 0);
  69443. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  69444. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  69445. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  69446. var transform = object.computeWorldMatrix(true);
  69447. // convert rawVerts to object space
  69448. var temp = new Array();
  69449. var index;
  69450. for (index = 0; index < rawVerts.length; index += 3) {
  69451. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  69452. }
  69453. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  69454. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  69455. //now set back the transformation!
  69456. object.position.copyFrom(oldPosition);
  69457. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  69458. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  69459. break;
  69460. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  69461. var oldPosition2 = object.position.clone();
  69462. var oldRotation2 = object.rotation && object.rotation.clone();
  69463. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  69464. object.position.copyFromFloats(0, 0, 0);
  69465. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  69466. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  69467. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  69468. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  69469. returnValue = this._createHeightmap(object);
  69470. object.position.copyFrom(oldPosition2);
  69471. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  69472. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  69473. object.computeWorldMatrix(true);
  69474. break;
  69475. case BABYLON.PhysicsImpostor.ParticleImpostor:
  69476. returnValue = new this.BJSCANNON.Particle();
  69477. break;
  69478. }
  69479. return returnValue;
  69480. };
  69481. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  69482. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  69483. var transform = object.computeWorldMatrix(true);
  69484. // convert rawVerts to object space
  69485. var temp = new Array();
  69486. var index;
  69487. for (index = 0; index < pos.length; index += 3) {
  69488. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  69489. }
  69490. pos = temp;
  69491. var matrix = new Array();
  69492. //For now pointDepth will not be used and will be automatically calculated.
  69493. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  69494. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  69495. var boundingInfo = object.getBoundingInfo();
  69496. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  69497. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  69498. var elementSize = dim * 2 / arraySize;
  69499. for (var i = 0; i < pos.length; i = i + 3) {
  69500. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  69501. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  69502. var y = -pos[i + 2] + minY;
  69503. if (!matrix[x]) {
  69504. matrix[x] = [];
  69505. }
  69506. if (!matrix[x][z]) {
  69507. matrix[x][z] = y;
  69508. }
  69509. matrix[x][z] = Math.max(y, matrix[x][z]);
  69510. }
  69511. for (var x = 0; x <= arraySize; ++x) {
  69512. if (!matrix[x]) {
  69513. var loc = 1;
  69514. while (!matrix[(x + loc) % arraySize]) {
  69515. loc++;
  69516. }
  69517. matrix[x] = matrix[(x + loc) % arraySize].slice();
  69518. //console.log("missing x", x);
  69519. }
  69520. for (var z = 0; z <= arraySize; ++z) {
  69521. if (!matrix[x][z]) {
  69522. var loc = 1;
  69523. var newValue;
  69524. while (newValue === undefined) {
  69525. newValue = matrix[x][(z + loc++) % arraySize];
  69526. }
  69527. matrix[x][z] = newValue;
  69528. }
  69529. }
  69530. }
  69531. var shape = new this.BJSCANNON.Heightfield(matrix, {
  69532. elementSize: elementSize
  69533. });
  69534. //For future reference, needed for body transformation
  69535. shape.minY = minY;
  69536. return shape;
  69537. };
  69538. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  69539. var object = impostor.object;
  69540. //make sure it is updated...
  69541. object.computeWorldMatrix && object.computeWorldMatrix(true);
  69542. // The delta between the mesh position and the mesh bounding box center
  69543. var bInfo = object.getBoundingInfo();
  69544. if (!bInfo)
  69545. return;
  69546. var center = impostor.getObjectCenter();
  69547. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  69548. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  69549. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  69550. this._tmpPosition.copyFrom(center);
  69551. var quaternion = object.rotationQuaternion;
  69552. if (!quaternion) {
  69553. return;
  69554. }
  69555. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  69556. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  69557. //-90 DEG in X, precalculated
  69558. quaternion = quaternion.multiply(this._minus90X);
  69559. //Invert! (Precalculated, 90 deg in X)
  69560. //No need to clone. this will never change.
  69561. impostor.setDeltaRotation(this._plus90X);
  69562. }
  69563. //If it is a heightfield, if should be centered.
  69564. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  69565. var mesh = object;
  69566. var boundingInfo = mesh.getBoundingInfo();
  69567. //calculate the correct body position:
  69568. var rotationQuaternion = mesh.rotationQuaternion;
  69569. mesh.rotationQuaternion = this._tmpUnityRotation;
  69570. mesh.computeWorldMatrix(true);
  69571. //get original center with no rotation
  69572. var c = center.clone();
  69573. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  69574. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  69575. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  69576. mesh.setPivotMatrix(p);
  69577. mesh.computeWorldMatrix(true);
  69578. //calculate the translation
  69579. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  69580. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  69581. //add it inverted to the delta
  69582. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  69583. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  69584. //rotation is back
  69585. mesh.rotationQuaternion = rotationQuaternion;
  69586. mesh.setPivotMatrix(oldPivot);
  69587. mesh.computeWorldMatrix(true);
  69588. }
  69589. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  69590. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  69591. //this._tmpPosition.copyFrom(object.position);
  69592. }
  69593. impostor.setDeltaPosition(this._tmpDeltaPosition);
  69594. //Now update the impostor object
  69595. impostor.physicsBody.position.copy(this._tmpPosition);
  69596. impostor.physicsBody.quaternion.copy(quaternion);
  69597. };
  69598. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  69599. impostor.object.position.copyFrom(impostor.physicsBody.position);
  69600. if (impostor.object.rotationQuaternion) {
  69601. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  69602. }
  69603. };
  69604. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  69605. impostor.physicsBody.position.copy(newPosition);
  69606. impostor.physicsBody.quaternion.copy(newRotation);
  69607. };
  69608. CannonJSPlugin.prototype.isSupported = function () {
  69609. return this.BJSCANNON !== undefined;
  69610. };
  69611. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  69612. impostor.physicsBody.velocity.copy(velocity);
  69613. };
  69614. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  69615. impostor.physicsBody.angularVelocity.copy(velocity);
  69616. };
  69617. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  69618. var v = impostor.physicsBody.velocity;
  69619. if (!v) {
  69620. return null;
  69621. }
  69622. return new BABYLON.Vector3(v.x, v.y, v.z);
  69623. };
  69624. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  69625. var v = impostor.physicsBody.angularVelocity;
  69626. if (!v) {
  69627. return null;
  69628. }
  69629. return new BABYLON.Vector3(v.x, v.y, v.z);
  69630. };
  69631. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  69632. impostor.physicsBody.mass = mass;
  69633. impostor.physicsBody.updateMassProperties();
  69634. };
  69635. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  69636. return impostor.physicsBody.mass;
  69637. };
  69638. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  69639. return impostor.physicsBody.material.friction;
  69640. };
  69641. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  69642. impostor.physicsBody.material.friction = friction;
  69643. };
  69644. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  69645. return impostor.physicsBody.material.restitution;
  69646. };
  69647. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  69648. impostor.physicsBody.material.restitution = restitution;
  69649. };
  69650. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  69651. impostor.physicsBody.sleep();
  69652. };
  69653. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  69654. impostor.physicsBody.wakeUp();
  69655. };
  69656. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  69657. joint.physicsJoint.distance = maxDistance;
  69658. };
  69659. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  69660. // if (!motorIndex) {
  69661. // joint.physicsJoint.enableMotor();
  69662. // }
  69663. // }
  69664. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  69665. // if (!motorIndex) {
  69666. // joint.physicsJoint.disableMotor();
  69667. // }
  69668. // }
  69669. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  69670. if (!motorIndex) {
  69671. joint.physicsJoint.enableMotor();
  69672. joint.physicsJoint.setMotorSpeed(speed);
  69673. if (maxForce) {
  69674. this.setLimit(joint, maxForce);
  69675. }
  69676. }
  69677. };
  69678. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  69679. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  69680. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  69681. };
  69682. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  69683. var body = impostor.physicsBody;
  69684. mesh.position.x = body.position.x;
  69685. mesh.position.y = body.position.y;
  69686. mesh.position.z = body.position.z;
  69687. if (mesh.rotationQuaternion) {
  69688. mesh.rotationQuaternion.x = body.quaternion.x;
  69689. mesh.rotationQuaternion.y = body.quaternion.y;
  69690. mesh.rotationQuaternion.z = body.quaternion.z;
  69691. mesh.rotationQuaternion.w = body.quaternion.w;
  69692. }
  69693. };
  69694. CannonJSPlugin.prototype.getRadius = function (impostor) {
  69695. var shape = impostor.physicsBody.shapes[0];
  69696. return shape.boundingSphereRadius;
  69697. };
  69698. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  69699. var shape = impostor.physicsBody.shapes[0];
  69700. result.x = shape.halfExtents.x * 2;
  69701. result.y = shape.halfExtents.y * 2;
  69702. result.z = shape.halfExtents.z * 2;
  69703. };
  69704. CannonJSPlugin.prototype.dispose = function () {
  69705. };
  69706. CannonJSPlugin.prototype._extendNamespace = function () {
  69707. //this will force cannon to execute at least one step when using interpolation
  69708. var step_tmp1 = new this.BJSCANNON.Vec3();
  69709. var Engine = this.BJSCANNON;
  69710. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  69711. maxSubSteps = maxSubSteps || 10;
  69712. timeSinceLastCalled = timeSinceLastCalled || 0;
  69713. if (timeSinceLastCalled === 0) {
  69714. this.internalStep(dt);
  69715. this.time += dt;
  69716. }
  69717. else {
  69718. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  69719. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  69720. var t0 = performance.now();
  69721. for (var i = 0; i !== internalSteps; i++) {
  69722. this.internalStep(dt);
  69723. if (performance.now() - t0 > dt * 1000) {
  69724. break;
  69725. }
  69726. }
  69727. this.time += timeSinceLastCalled;
  69728. var h = this.time % dt;
  69729. var h_div_dt = h / dt;
  69730. var interpvelo = step_tmp1;
  69731. var bodies = this.bodies;
  69732. for (var j = 0; j !== bodies.length; j++) {
  69733. var b = bodies[j];
  69734. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  69735. b.position.vsub(b.previousPosition, interpvelo);
  69736. interpvelo.scale(h_div_dt, interpvelo);
  69737. b.position.vadd(interpvelo, b.interpolatedPosition);
  69738. }
  69739. else {
  69740. b.interpolatedPosition.copy(b.position);
  69741. b.interpolatedQuaternion.copy(b.quaternion);
  69742. }
  69743. }
  69744. }
  69745. };
  69746. };
  69747. return CannonJSPlugin;
  69748. }());
  69749. BABYLON.CannonJSPlugin = CannonJSPlugin;
  69750. })(BABYLON || (BABYLON = {}));
  69751. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  69752. var BABYLON;
  69753. (function (BABYLON) {
  69754. var OimoJSPlugin = /** @class */ (function () {
  69755. function OimoJSPlugin(iterations) {
  69756. this.name = "OimoJSPlugin";
  69757. this._tmpImpostorsArray = [];
  69758. this._tmpPositionVector = BABYLON.Vector3.Zero();
  69759. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  69760. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  69761. this.world.worldscale(1);
  69762. this.world.clear();
  69763. //making sure no stats are calculated
  69764. this.world.isNoStat = true;
  69765. }
  69766. OimoJSPlugin.prototype.setGravity = function (gravity) {
  69767. this.world.gravity.copy(gravity);
  69768. };
  69769. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  69770. this.world.timeStep = timeStep;
  69771. };
  69772. OimoJSPlugin.prototype.getTimeStep = function () {
  69773. return this.world.timeStep;
  69774. };
  69775. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  69776. var _this = this;
  69777. impostors.forEach(function (impostor) {
  69778. impostor.beforeStep();
  69779. });
  69780. this.world.step();
  69781. impostors.forEach(function (impostor) {
  69782. impostor.afterStep();
  69783. //update the ordered impostors array
  69784. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  69785. });
  69786. //check for collisions
  69787. var contact = this.world.contacts;
  69788. while (contact !== null) {
  69789. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  69790. contact = contact.next;
  69791. continue;
  69792. }
  69793. //is this body colliding with any other? get the impostor
  69794. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  69795. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  69796. if (!mainImpostor || !collidingImpostor) {
  69797. contact = contact.next;
  69798. continue;
  69799. }
  69800. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  69801. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  69802. contact = contact.next;
  69803. }
  69804. };
  69805. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  69806. var mass = impostor.physicsBody.massInfo.mass;
  69807. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  69808. };
  69809. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  69810. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  69811. this.applyImpulse(impostor, force, contactPoint);
  69812. };
  69813. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  69814. var _this = this;
  69815. //parent-child relationship. Does this impostor has a parent impostor?
  69816. if (impostor.parent) {
  69817. if (impostor.physicsBody) {
  69818. this.removePhysicsBody(impostor);
  69819. //TODO is that needed?
  69820. impostor.forceUpdate();
  69821. }
  69822. return;
  69823. }
  69824. if (impostor.isBodyInitRequired()) {
  69825. var bodyConfig = {
  69826. name: impostor.uniqueId,
  69827. //Oimo must have mass, also for static objects.
  69828. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  69829. size: [],
  69830. type: [],
  69831. pos: [],
  69832. rot: [],
  69833. move: impostor.getParam("mass") !== 0,
  69834. //Supporting older versions of Oimo
  69835. world: this.world
  69836. };
  69837. var impostors = [impostor];
  69838. var addToArray = function (parent) {
  69839. if (!parent.getChildMeshes)
  69840. return;
  69841. parent.getChildMeshes().forEach(function (m) {
  69842. if (m.physicsImpostor) {
  69843. impostors.push(m.physicsImpostor);
  69844. //m.physicsImpostor._init();
  69845. }
  69846. });
  69847. };
  69848. addToArray(impostor.object);
  69849. var checkWithEpsilon_1 = function (value) {
  69850. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  69851. };
  69852. impostors.forEach(function (i) {
  69853. if (!impostor.object.rotationQuaternion) {
  69854. return;
  69855. }
  69856. //get the correct bounding box
  69857. var oldQuaternion = i.object.rotationQuaternion;
  69858. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  69859. x: impostor.object.rotationQuaternion.x,
  69860. y: impostor.object.rotationQuaternion.y,
  69861. z: impostor.object.rotationQuaternion.z,
  69862. s: impostor.object.rotationQuaternion.w
  69863. });
  69864. var extendSize = i.getObjectExtendSize();
  69865. if (i === impostor) {
  69866. var center = impostor.getObjectCenter();
  69867. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  69868. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  69869. //Can also use Array.prototype.push.apply
  69870. bodyConfig.pos.push(center.x);
  69871. bodyConfig.pos.push(center.y);
  69872. bodyConfig.pos.push(center.z);
  69873. //tmp solution
  69874. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69875. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69876. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69877. }
  69878. else {
  69879. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  69880. bodyConfig.pos.push(localPosition.x);
  69881. bodyConfig.pos.push(localPosition.y);
  69882. bodyConfig.pos.push(localPosition.z);
  69883. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  69884. bodyConfig.rot.push(0);
  69885. bodyConfig.rot.push(0);
  69886. bodyConfig.rot.push(0);
  69887. }
  69888. // register mesh
  69889. switch (i.type) {
  69890. case BABYLON.PhysicsImpostor.ParticleImpostor:
  69891. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  69892. case BABYLON.PhysicsImpostor.SphereImpostor:
  69893. var radiusX = extendSize.x;
  69894. var radiusY = extendSize.y;
  69895. var radiusZ = extendSize.z;
  69896. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  69897. bodyConfig.type.push('sphere');
  69898. //due to the way oimo works with compounds, add 3 times
  69899. bodyConfig.size.push(size);
  69900. bodyConfig.size.push(size);
  69901. bodyConfig.size.push(size);
  69902. break;
  69903. case BABYLON.PhysicsImpostor.CylinderImpostor:
  69904. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  69905. var sizeY = checkWithEpsilon_1(extendSize.y);
  69906. bodyConfig.type.push('cylinder');
  69907. bodyConfig.size.push(sizeX);
  69908. bodyConfig.size.push(sizeY);
  69909. //due to the way oimo works with compounds, add one more value.
  69910. bodyConfig.size.push(sizeY);
  69911. break;
  69912. case BABYLON.PhysicsImpostor.PlaneImpostor:
  69913. case BABYLON.PhysicsImpostor.BoxImpostor:
  69914. default:
  69915. var sizeX = checkWithEpsilon_1(extendSize.x);
  69916. var sizeY = checkWithEpsilon_1(extendSize.y);
  69917. var sizeZ = checkWithEpsilon_1(extendSize.z);
  69918. bodyConfig.type.push('box');
  69919. bodyConfig.size.push(sizeX);
  69920. bodyConfig.size.push(sizeY);
  69921. bodyConfig.size.push(sizeZ);
  69922. break;
  69923. }
  69924. //actually not needed, but hey...
  69925. i.object.rotationQuaternion = oldQuaternion;
  69926. });
  69927. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  69928. }
  69929. else {
  69930. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  69931. }
  69932. impostor.setDeltaPosition(this._tmpPositionVector);
  69933. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  69934. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  69935. };
  69936. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  69937. //impostor.physicsBody.dispose();
  69938. //Same as : (older oimo versions)
  69939. this.world.removeRigidBody(impostor.physicsBody);
  69940. };
  69941. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  69942. var mainBody = impostorJoint.mainImpostor.physicsBody;
  69943. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  69944. if (!mainBody || !connectedBody) {
  69945. return;
  69946. }
  69947. var jointData = impostorJoint.joint.jointData;
  69948. var options = jointData.nativeParams || {};
  69949. var type;
  69950. var nativeJointData = {
  69951. body1: mainBody,
  69952. body2: connectedBody,
  69953. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  69954. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  69955. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  69956. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  69957. min: options.min,
  69958. max: options.max,
  69959. collision: options.collision || jointData.collision,
  69960. spring: options.spring,
  69961. //supporting older version of Oimo
  69962. world: this.world
  69963. };
  69964. switch (impostorJoint.joint.type) {
  69965. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  69966. type = "jointBall";
  69967. break;
  69968. case BABYLON.PhysicsJoint.SpringJoint:
  69969. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  69970. var springData = jointData;
  69971. nativeJointData.min = springData.length || nativeJointData.min;
  69972. //Max should also be set, just make sure it is at least min
  69973. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  69974. case BABYLON.PhysicsJoint.DistanceJoint:
  69975. type = "jointDistance";
  69976. nativeJointData.max = jointData.maxDistance;
  69977. break;
  69978. case BABYLON.PhysicsJoint.PrismaticJoint:
  69979. type = "jointPrisme";
  69980. break;
  69981. case BABYLON.PhysicsJoint.SliderJoint:
  69982. type = "jointSlide";
  69983. break;
  69984. case BABYLON.PhysicsJoint.WheelJoint:
  69985. type = "jointWheel";
  69986. break;
  69987. case BABYLON.PhysicsJoint.HingeJoint:
  69988. default:
  69989. type = "jointHinge";
  69990. break;
  69991. }
  69992. nativeJointData.type = type;
  69993. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  69994. };
  69995. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  69996. //Bug in Oimo prevents us from disposing a joint in the playground
  69997. //joint.joint.physicsJoint.dispose();
  69998. //So we will bruteforce it!
  69999. try {
  70000. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  70001. }
  70002. catch (e) {
  70003. BABYLON.Tools.Warn(e);
  70004. }
  70005. };
  70006. OimoJSPlugin.prototype.isSupported = function () {
  70007. return this.BJSOIMO !== undefined;
  70008. };
  70009. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  70010. if (!impostor.physicsBody.sleeping) {
  70011. //TODO check that
  70012. if (impostor.physicsBody.shapes.next) {
  70013. var parentShape = this._getLastShape(impostor.physicsBody);
  70014. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  70015. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  70016. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  70017. }
  70018. else {
  70019. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  70020. }
  70021. if (impostor.object.rotationQuaternion) {
  70022. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  70023. impostor.object.rotationQuaternion.normalize();
  70024. }
  70025. }
  70026. };
  70027. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  70028. var body = impostor.physicsBody;
  70029. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  70030. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  70031. body.syncShapes();
  70032. body.awake();
  70033. };
  70034. OimoJSPlugin.prototype._getLastShape = function (body) {
  70035. var lastShape = body.shapes;
  70036. while (lastShape.next) {
  70037. lastShape = lastShape.next;
  70038. }
  70039. return lastShape;
  70040. };
  70041. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  70042. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  70043. };
  70044. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  70045. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  70046. };
  70047. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  70048. var v = impostor.physicsBody.linearVelocity;
  70049. if (!v) {
  70050. return null;
  70051. }
  70052. return new BABYLON.Vector3(v.x, v.y, v.z);
  70053. };
  70054. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  70055. var v = impostor.physicsBody.angularVelocity;
  70056. if (!v) {
  70057. return null;
  70058. }
  70059. return new BABYLON.Vector3(v.x, v.y, v.z);
  70060. };
  70061. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  70062. var staticBody = mass === 0;
  70063. //this will actually set the body's density and not its mass.
  70064. //But this is how oimo treats the mass variable.
  70065. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  70066. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  70067. };
  70068. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  70069. return impostor.physicsBody.shapes.density;
  70070. };
  70071. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  70072. return impostor.physicsBody.shapes.friction;
  70073. };
  70074. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  70075. impostor.physicsBody.shapes.friction = friction;
  70076. };
  70077. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  70078. return impostor.physicsBody.shapes.restitution;
  70079. };
  70080. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  70081. impostor.physicsBody.shapes.restitution = restitution;
  70082. };
  70083. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  70084. impostor.physicsBody.sleep();
  70085. };
  70086. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  70087. impostor.physicsBody.awake();
  70088. };
  70089. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  70090. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  70091. if (minDistance !== void 0) {
  70092. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  70093. }
  70094. };
  70095. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  70096. //TODO separate rotational and transational motors.
  70097. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  70098. if (motor) {
  70099. motor.setMotor(speed, maxForce);
  70100. }
  70101. };
  70102. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  70103. //TODO separate rotational and transational motors.
  70104. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  70105. if (motor) {
  70106. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  70107. }
  70108. };
  70109. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  70110. var body = impostor.physicsBody;
  70111. mesh.position.x = body.position.x;
  70112. mesh.position.y = body.position.y;
  70113. mesh.position.z = body.position.z;
  70114. if (mesh.rotationQuaternion) {
  70115. mesh.rotationQuaternion.x = body.orientation.x;
  70116. mesh.rotationQuaternion.y = body.orientation.y;
  70117. mesh.rotationQuaternion.z = body.orientation.z;
  70118. mesh.rotationQuaternion.w = body.orientation.s;
  70119. }
  70120. };
  70121. OimoJSPlugin.prototype.getRadius = function (impostor) {
  70122. return impostor.physicsBody.shapes.radius;
  70123. };
  70124. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  70125. var shape = impostor.physicsBody.shapes;
  70126. result.x = shape.halfWidth * 2;
  70127. result.y = shape.halfHeight * 2;
  70128. result.z = shape.halfDepth * 2;
  70129. };
  70130. OimoJSPlugin.prototype.dispose = function () {
  70131. this.world.clear();
  70132. };
  70133. return OimoJSPlugin;
  70134. }());
  70135. BABYLON.OimoJSPlugin = OimoJSPlugin;
  70136. })(BABYLON || (BABYLON = {}));
  70137. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  70138. var BABYLON;
  70139. (function (BABYLON) {
  70140. /*
  70141. * Based on jsTGALoader - Javascript loader for TGA file
  70142. * By Vincent Thibault
  70143. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  70144. */
  70145. var TGATools = /** @class */ (function () {
  70146. function TGATools() {
  70147. }
  70148. TGATools.GetTGAHeader = function (data) {
  70149. var offset = 0;
  70150. var header = {
  70151. id_length: data[offset++],
  70152. colormap_type: data[offset++],
  70153. image_type: data[offset++],
  70154. colormap_index: data[offset++] | data[offset++] << 8,
  70155. colormap_length: data[offset++] | data[offset++] << 8,
  70156. colormap_size: data[offset++],
  70157. origin: [
  70158. data[offset++] | data[offset++] << 8,
  70159. data[offset++] | data[offset++] << 8
  70160. ],
  70161. width: data[offset++] | data[offset++] << 8,
  70162. height: data[offset++] | data[offset++] << 8,
  70163. pixel_size: data[offset++],
  70164. flags: data[offset++]
  70165. };
  70166. return header;
  70167. };
  70168. TGATools.UploadContent = function (gl, data) {
  70169. // Not enough data to contain header ?
  70170. if (data.length < 19) {
  70171. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  70172. return;
  70173. }
  70174. // Read Header
  70175. var offset = 18;
  70176. var header = TGATools.GetTGAHeader(data);
  70177. // Assume it's a valid Targa file.
  70178. if (header.id_length + offset > data.length) {
  70179. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  70180. return;
  70181. }
  70182. // Skip not needed data
  70183. offset += header.id_length;
  70184. var use_rle = false;
  70185. var use_pal = false;
  70186. var use_grey = false;
  70187. // Get some informations.
  70188. switch (header.image_type) {
  70189. case TGATools._TYPE_RLE_INDEXED:
  70190. use_rle = true;
  70191. case TGATools._TYPE_INDEXED:
  70192. use_pal = true;
  70193. break;
  70194. case TGATools._TYPE_RLE_RGB:
  70195. use_rle = true;
  70196. case TGATools._TYPE_RGB:
  70197. // use_rgb = true;
  70198. break;
  70199. case TGATools._TYPE_RLE_GREY:
  70200. use_rle = true;
  70201. case TGATools._TYPE_GREY:
  70202. use_grey = true;
  70203. break;
  70204. }
  70205. var pixel_data;
  70206. // var numAlphaBits = header.flags & 0xf;
  70207. var pixel_size = header.pixel_size >> 3;
  70208. var pixel_total = header.width * header.height * pixel_size;
  70209. // Read palettes
  70210. var palettes;
  70211. if (use_pal) {
  70212. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  70213. }
  70214. // Read LRE
  70215. if (use_rle) {
  70216. pixel_data = new Uint8Array(pixel_total);
  70217. var c, count, i;
  70218. var localOffset = 0;
  70219. var pixels = new Uint8Array(pixel_size);
  70220. while (offset < pixel_total && localOffset < pixel_total) {
  70221. c = data[offset++];
  70222. count = (c & 0x7f) + 1;
  70223. // RLE pixels
  70224. if (c & 0x80) {
  70225. // Bind pixel tmp array
  70226. for (i = 0; i < pixel_size; ++i) {
  70227. pixels[i] = data[offset++];
  70228. }
  70229. // Copy pixel array
  70230. for (i = 0; i < count; ++i) {
  70231. pixel_data.set(pixels, localOffset + i * pixel_size);
  70232. }
  70233. localOffset += pixel_size * count;
  70234. }
  70235. else {
  70236. count *= pixel_size;
  70237. for (i = 0; i < count; ++i) {
  70238. pixel_data[localOffset + i] = data[offset++];
  70239. }
  70240. localOffset += count;
  70241. }
  70242. }
  70243. }
  70244. else {
  70245. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  70246. }
  70247. // Load to texture
  70248. var x_start, y_start, x_step, y_step, y_end, x_end;
  70249. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  70250. default:
  70251. case TGATools._ORIGIN_UL:
  70252. x_start = 0;
  70253. x_step = 1;
  70254. x_end = header.width;
  70255. y_start = 0;
  70256. y_step = 1;
  70257. y_end = header.height;
  70258. break;
  70259. case TGATools._ORIGIN_BL:
  70260. x_start = 0;
  70261. x_step = 1;
  70262. x_end = header.width;
  70263. y_start = header.height - 1;
  70264. y_step = -1;
  70265. y_end = -1;
  70266. break;
  70267. case TGATools._ORIGIN_UR:
  70268. x_start = header.width - 1;
  70269. x_step = -1;
  70270. x_end = -1;
  70271. y_start = 0;
  70272. y_step = 1;
  70273. y_end = header.height;
  70274. break;
  70275. case TGATools._ORIGIN_BR:
  70276. x_start = header.width - 1;
  70277. x_step = -1;
  70278. x_end = -1;
  70279. y_start = header.height - 1;
  70280. y_step = -1;
  70281. y_end = -1;
  70282. break;
  70283. }
  70284. // Load the specify method
  70285. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  70286. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  70287. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  70288. };
  70289. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70290. var image = pixel_data, colormap = palettes;
  70291. var width = header.width, height = header.height;
  70292. var color, i = 0, x, y;
  70293. var imageData = new Uint8Array(width * height * 4);
  70294. for (y = y_start; y !== y_end; y += y_step) {
  70295. for (x = x_start; x !== x_end; x += x_step, i++) {
  70296. color = image[i];
  70297. imageData[(x + width * y) * 4 + 3] = 255;
  70298. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  70299. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  70300. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  70301. }
  70302. }
  70303. return imageData;
  70304. };
  70305. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70306. var image = pixel_data;
  70307. var width = header.width, height = header.height;
  70308. var color, i = 0, x, y;
  70309. var imageData = new Uint8Array(width * height * 4);
  70310. for (y = y_start; y !== y_end; y += y_step) {
  70311. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  70312. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  70313. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  70314. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  70315. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  70316. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  70317. }
  70318. }
  70319. return imageData;
  70320. };
  70321. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70322. var image = pixel_data;
  70323. var width = header.width, height = header.height;
  70324. var i = 0, x, y;
  70325. var imageData = new Uint8Array(width * height * 4);
  70326. for (y = y_start; y !== y_end; y += y_step) {
  70327. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  70328. imageData[(x + width * y) * 4 + 3] = 255;
  70329. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70330. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  70331. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  70332. }
  70333. }
  70334. return imageData;
  70335. };
  70336. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70337. var image = pixel_data;
  70338. var width = header.width, height = header.height;
  70339. var i = 0, x, y;
  70340. var imageData = new Uint8Array(width * height * 4);
  70341. for (y = y_start; y !== y_end; y += y_step) {
  70342. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  70343. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70344. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  70345. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  70346. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  70347. }
  70348. }
  70349. return imageData;
  70350. };
  70351. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70352. var image = pixel_data;
  70353. var width = header.width, height = header.height;
  70354. var color, i = 0, x, y;
  70355. var imageData = new Uint8Array(width * height * 4);
  70356. for (y = y_start; y !== y_end; y += y_step) {
  70357. for (x = x_start; x !== x_end; x += x_step, i++) {
  70358. color = image[i];
  70359. imageData[(x + width * y) * 4 + 0] = color;
  70360. imageData[(x + width * y) * 4 + 1] = color;
  70361. imageData[(x + width * y) * 4 + 2] = color;
  70362. imageData[(x + width * y) * 4 + 3] = 255;
  70363. }
  70364. }
  70365. return imageData;
  70366. };
  70367. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70368. var image = pixel_data;
  70369. var width = header.width, height = header.height;
  70370. var i = 0, x, y;
  70371. var imageData = new Uint8Array(width * height * 4);
  70372. for (y = y_start; y !== y_end; y += y_step) {
  70373. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  70374. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  70375. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  70376. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70377. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  70378. }
  70379. }
  70380. return imageData;
  70381. };
  70382. //private static _TYPE_NO_DATA = 0;
  70383. TGATools._TYPE_INDEXED = 1;
  70384. TGATools._TYPE_RGB = 2;
  70385. TGATools._TYPE_GREY = 3;
  70386. TGATools._TYPE_RLE_INDEXED = 9;
  70387. TGATools._TYPE_RLE_RGB = 10;
  70388. TGATools._TYPE_RLE_GREY = 11;
  70389. TGATools._ORIGIN_MASK = 0x30;
  70390. TGATools._ORIGIN_SHIFT = 0x04;
  70391. TGATools._ORIGIN_BL = 0x00;
  70392. TGATools._ORIGIN_BR = 0x01;
  70393. TGATools._ORIGIN_UL = 0x02;
  70394. TGATools._ORIGIN_UR = 0x03;
  70395. return TGATools;
  70396. }());
  70397. BABYLON.TGATools = TGATools;
  70398. })(BABYLON || (BABYLON = {}));
  70399. //# sourceMappingURL=babylon.tga.js.map
  70400. var BABYLON;
  70401. (function (BABYLON) {
  70402. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  70403. // All values and structures referenced from:
  70404. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  70405. var DDS_MAGIC = 0x20534444;
  70406. var
  70407. //DDSD_CAPS = 0x1,
  70408. //DDSD_HEIGHT = 0x2,
  70409. //DDSD_WIDTH = 0x4,
  70410. //DDSD_PITCH = 0x8,
  70411. //DDSD_PIXELFORMAT = 0x1000,
  70412. DDSD_MIPMAPCOUNT = 0x20000;
  70413. //DDSD_LINEARSIZE = 0x80000,
  70414. //DDSD_DEPTH = 0x800000;
  70415. // var DDSCAPS_COMPLEX = 0x8,
  70416. // DDSCAPS_MIPMAP = 0x400000,
  70417. // DDSCAPS_TEXTURE = 0x1000;
  70418. var DDSCAPS2_CUBEMAP = 0x200;
  70419. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  70420. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  70421. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  70422. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  70423. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  70424. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  70425. // DDSCAPS2_VOLUME = 0x200000;
  70426. var
  70427. //DDPF_ALPHAPIXELS = 0x1,
  70428. //DDPF_ALPHA = 0x2,
  70429. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  70430. //DDPF_YUV = 0x200,
  70431. DDPF_LUMINANCE = 0x20000;
  70432. function FourCCToInt32(value) {
  70433. return value.charCodeAt(0) +
  70434. (value.charCodeAt(1) << 8) +
  70435. (value.charCodeAt(2) << 16) +
  70436. (value.charCodeAt(3) << 24);
  70437. }
  70438. function Int32ToFourCC(value) {
  70439. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  70440. }
  70441. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  70442. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  70443. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  70444. var FOURCC_DX10 = FourCCToInt32("DX10");
  70445. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  70446. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  70447. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  70448. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  70449. var headerLengthInt = 31; // The header length in 32 bit ints
  70450. // Offsets into the header array
  70451. var off_magic = 0;
  70452. var off_size = 1;
  70453. var off_flags = 2;
  70454. var off_height = 3;
  70455. var off_width = 4;
  70456. var off_mipmapCount = 7;
  70457. var off_pfFlags = 20;
  70458. var off_pfFourCC = 21;
  70459. var off_RGBbpp = 22;
  70460. // var off_RMask = 23;
  70461. // var off_GMask = 24;
  70462. // var off_BMask = 25;
  70463. // var off_AMask = 26;
  70464. // var off_caps1 = 27;
  70465. var off_caps2 = 28;
  70466. // var off_caps3 = 29;
  70467. // var off_caps4 = 30;
  70468. var off_dxgiFormat = 32;
  70469. ;
  70470. var DDSTools = /** @class */ (function () {
  70471. function DDSTools() {
  70472. }
  70473. DDSTools.GetDDSInfo = function (arrayBuffer) {
  70474. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70475. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  70476. var mipmapCount = 1;
  70477. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  70478. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70479. }
  70480. var fourCC = header[off_pfFourCC];
  70481. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  70482. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70483. switch (fourCC) {
  70484. case FOURCC_D3DFMT_R16G16B16A16F:
  70485. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70486. break;
  70487. case FOURCC_D3DFMT_R32G32B32A32F:
  70488. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70489. break;
  70490. case FOURCC_DX10:
  70491. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  70492. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70493. break;
  70494. }
  70495. }
  70496. return {
  70497. width: header[off_width],
  70498. height: header[off_height],
  70499. mipmapCount: mipmapCount,
  70500. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  70501. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  70502. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  70503. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  70504. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  70505. dxgiFormat: dxgiFormat,
  70506. textureType: textureType
  70507. };
  70508. };
  70509. DDSTools._ToHalfFloat = function (value) {
  70510. if (!DDSTools._FloatView) {
  70511. DDSTools._FloatView = new Float32Array(1);
  70512. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  70513. }
  70514. DDSTools._FloatView[0] = value;
  70515. var x = DDSTools._Int32View[0];
  70516. var bits = (x >> 16) & 0x8000; /* Get the sign */
  70517. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  70518. var e = (x >> 23) & 0xff; /* Using int is faster here */
  70519. /* If zero, or denormal, or exponent underflows too much for a denormal
  70520. * half, return signed zero. */
  70521. if (e < 103) {
  70522. return bits;
  70523. }
  70524. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  70525. if (e > 142) {
  70526. bits |= 0x7c00;
  70527. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  70528. * not Inf, so make sure we set one mantissa bit too. */
  70529. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  70530. return bits;
  70531. }
  70532. /* If exponent underflows but not too much, return a denormal */
  70533. if (e < 113) {
  70534. m |= 0x0800;
  70535. /* Extra rounding may overflow and set mantissa to 0 and exponent
  70536. * to 1, which is OK. */
  70537. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  70538. return bits;
  70539. }
  70540. bits |= ((e - 112) << 10) | (m >> 1);
  70541. bits += m & 1;
  70542. return bits;
  70543. };
  70544. DDSTools._FromHalfFloat = function (value) {
  70545. var s = (value & 0x8000) >> 15;
  70546. var e = (value & 0x7C00) >> 10;
  70547. var f = value & 0x03FF;
  70548. if (e === 0) {
  70549. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  70550. }
  70551. else if (e == 0x1F) {
  70552. return f ? NaN : ((s ? -1 : 1) * Infinity);
  70553. }
  70554. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  70555. };
  70556. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70557. var destArray = new Float32Array(dataLength);
  70558. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70559. var index = 0;
  70560. for (var y = 0; y < height; y++) {
  70561. for (var x = 0; x < width; x++) {
  70562. var srcPos = (x + y * width) * 4;
  70563. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  70564. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  70565. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  70566. if (DDSTools.StoreLODInAlphaChannel) {
  70567. destArray[index + 3] = lod;
  70568. }
  70569. else {
  70570. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  70571. }
  70572. index += 4;
  70573. }
  70574. }
  70575. return destArray;
  70576. };
  70577. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70578. if (DDSTools.StoreLODInAlphaChannel) {
  70579. var destArray = new Uint16Array(dataLength);
  70580. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70581. var index = 0;
  70582. for (var y = 0; y < height; y++) {
  70583. for (var x = 0; x < width; x++) {
  70584. var srcPos = (x + y * width) * 4;
  70585. destArray[index] = srcData[srcPos];
  70586. destArray[index + 1] = srcData[srcPos + 1];
  70587. destArray[index + 2] = srcData[srcPos + 2];
  70588. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  70589. index += 4;
  70590. }
  70591. }
  70592. return destArray;
  70593. }
  70594. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  70595. };
  70596. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70597. if (DDSTools.StoreLODInAlphaChannel) {
  70598. var destArray = new Float32Array(dataLength);
  70599. var srcData = new Float32Array(arrayBuffer, dataOffset);
  70600. var index = 0;
  70601. for (var y = 0; y < height; y++) {
  70602. for (var x = 0; x < width; x++) {
  70603. var srcPos = (x + y * width) * 4;
  70604. destArray[index] = srcData[srcPos];
  70605. destArray[index + 1] = srcData[srcPos + 1];
  70606. destArray[index + 2] = srcData[srcPos + 2];
  70607. destArray[index + 3] = lod;
  70608. index += 4;
  70609. }
  70610. }
  70611. return destArray;
  70612. }
  70613. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  70614. };
  70615. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70616. var destArray = new Uint8Array(dataLength);
  70617. var srcData = new Float32Array(arrayBuffer, dataOffset);
  70618. var index = 0;
  70619. for (var y = 0; y < height; y++) {
  70620. for (var x = 0; x < width; x++) {
  70621. var srcPos = (x + y * width) * 4;
  70622. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  70623. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  70624. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  70625. if (DDSTools.StoreLODInAlphaChannel) {
  70626. destArray[index + 3] = lod;
  70627. }
  70628. else {
  70629. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  70630. }
  70631. index += 4;
  70632. }
  70633. }
  70634. return destArray;
  70635. };
  70636. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70637. var destArray = new Uint8Array(dataLength);
  70638. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70639. var index = 0;
  70640. for (var y = 0; y < height; y++) {
  70641. for (var x = 0; x < width; x++) {
  70642. var srcPos = (x + y * width) * 4;
  70643. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  70644. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  70645. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  70646. if (DDSTools.StoreLODInAlphaChannel) {
  70647. destArray[index + 3] = lod;
  70648. }
  70649. else {
  70650. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  70651. }
  70652. index += 4;
  70653. }
  70654. }
  70655. return destArray;
  70656. };
  70657. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70658. var byteArray = new Uint8Array(dataLength);
  70659. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70660. var index = 0;
  70661. for (var y = 0; y < height; y++) {
  70662. for (var x = 0; x < width; x++) {
  70663. var srcPos = (x + y * width) * 4;
  70664. byteArray[index] = srcData[srcPos + 2];
  70665. byteArray[index + 1] = srcData[srcPos + 1];
  70666. byteArray[index + 2] = srcData[srcPos];
  70667. byteArray[index + 3] = srcData[srcPos + 3];
  70668. index += 4;
  70669. }
  70670. }
  70671. return byteArray;
  70672. };
  70673. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70674. var byteArray = new Uint8Array(dataLength);
  70675. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70676. var index = 0;
  70677. for (var y = 0; y < height; y++) {
  70678. for (var x = 0; x < width; x++) {
  70679. var srcPos = (x + y * width) * 3;
  70680. byteArray[index] = srcData[srcPos + 2];
  70681. byteArray[index + 1] = srcData[srcPos + 1];
  70682. byteArray[index + 2] = srcData[srcPos];
  70683. index += 3;
  70684. }
  70685. }
  70686. return byteArray;
  70687. };
  70688. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70689. var byteArray = new Uint8Array(dataLength);
  70690. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70691. var index = 0;
  70692. for (var y = 0; y < height; y++) {
  70693. for (var x = 0; x < width; x++) {
  70694. var srcPos = (x + y * width);
  70695. byteArray[index] = srcData[srcPos];
  70696. index++;
  70697. }
  70698. }
  70699. return byteArray;
  70700. };
  70701. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  70702. if (lodIndex === void 0) { lodIndex = -1; }
  70703. var ext = engine.getCaps().s3tc;
  70704. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70705. var fourCC, width, height, dataLength = 0, dataOffset;
  70706. var byteArray, mipmapCount, mip;
  70707. var internalFormat = 0;
  70708. var format = 0;
  70709. var blockBytes = 1;
  70710. if (header[off_magic] !== DDS_MAGIC) {
  70711. BABYLON.Tools.Error("Invalid magic number in DDS header");
  70712. return;
  70713. }
  70714. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  70715. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  70716. return;
  70717. }
  70718. if (info.isCompressed && !ext) {
  70719. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  70720. return;
  70721. }
  70722. var bpp = header[off_RGBbpp];
  70723. dataOffset = header[off_size] + 4;
  70724. var computeFormats = false;
  70725. if (info.isFourCC) {
  70726. fourCC = header[off_pfFourCC];
  70727. switch (fourCC) {
  70728. case FOURCC_DXT1:
  70729. blockBytes = 8;
  70730. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  70731. break;
  70732. case FOURCC_DXT3:
  70733. blockBytes = 16;
  70734. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  70735. break;
  70736. case FOURCC_DXT5:
  70737. blockBytes = 16;
  70738. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  70739. break;
  70740. case FOURCC_D3DFMT_R16G16B16A16F:
  70741. computeFormats = true;
  70742. break;
  70743. case FOURCC_D3DFMT_R32G32B32A32F:
  70744. computeFormats = true;
  70745. break;
  70746. case FOURCC_DX10:
  70747. // There is an additionnal header so dataOffset need to be changed
  70748. dataOffset += 5 * 4; // 5 uints
  70749. var supported = false;
  70750. switch (info.dxgiFormat) {
  70751. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  70752. computeFormats = true;
  70753. supported = true;
  70754. break;
  70755. case DXGI_FORMAT_B8G8R8X8_UNORM:
  70756. info.isRGB = true;
  70757. info.isFourCC = false;
  70758. bpp = 32;
  70759. supported = true;
  70760. break;
  70761. }
  70762. if (supported) {
  70763. break;
  70764. }
  70765. default:
  70766. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  70767. return;
  70768. }
  70769. }
  70770. if (computeFormats) {
  70771. format = engine._getWebGLTextureType(info.textureType);
  70772. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70773. }
  70774. mipmapCount = 1;
  70775. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  70776. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70777. }
  70778. for (var face = 0; face < faces; face++) {
  70779. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  70780. width = header[off_width];
  70781. height = header[off_height];
  70782. for (mip = 0; mip < mipmapCount; ++mip) {
  70783. if (lodIndex === -1 || lodIndex === mip) {
  70784. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  70785. var i = (lodIndex === -1) ? mip : 0;
  70786. if (!info.isCompressed && info.isFourCC) {
  70787. dataLength = width * height * 4;
  70788. var floatArray = null;
  70789. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  70790. if (bpp === 128) {
  70791. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70792. }
  70793. else if (bpp === 64) {
  70794. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70795. }
  70796. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70797. format = engine._getWebGLTextureType(info.textureType);
  70798. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70799. }
  70800. else {
  70801. if (bpp === 128) {
  70802. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70803. }
  70804. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  70805. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70806. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70807. format = engine._getWebGLTextureType(info.textureType);
  70808. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70809. }
  70810. else {
  70811. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70812. }
  70813. }
  70814. if (floatArray) {
  70815. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  70816. }
  70817. }
  70818. else if (info.isRGB) {
  70819. if (bpp === 24) {
  70820. dataLength = width * height * 3;
  70821. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70822. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  70823. }
  70824. else {
  70825. dataLength = width * height * 4;
  70826. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70827. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  70828. }
  70829. }
  70830. else if (info.isLuminance) {
  70831. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  70832. var unpaddedRowSize = width;
  70833. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  70834. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  70835. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70836. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  70837. }
  70838. else {
  70839. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  70840. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  70841. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  70842. }
  70843. }
  70844. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  70845. width *= 0.5;
  70846. height *= 0.5;
  70847. width = Math.max(1.0, width);
  70848. height = Math.max(1.0, height);
  70849. }
  70850. if (currentFace !== undefined) {
  70851. // Loading a single face
  70852. break;
  70853. }
  70854. }
  70855. };
  70856. DDSTools.StoreLODInAlphaChannel = false;
  70857. return DDSTools;
  70858. }());
  70859. BABYLON.DDSTools = DDSTools;
  70860. })(BABYLON || (BABYLON = {}));
  70861. //# sourceMappingURL=babylon.dds.js.map
  70862. var BABYLON;
  70863. (function (BABYLON) {
  70864. /**
  70865. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  70866. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  70867. */
  70868. var KhronosTextureContainer = /** @class */ (function () {
  70869. /**
  70870. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  70871. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  70872. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  70873. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  70874. */
  70875. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  70876. this.arrayBuffer = arrayBuffer;
  70877. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  70878. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  70879. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  70880. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  70881. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  70882. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  70883. BABYLON.Tools.Error("texture missing KTX identifier");
  70884. return;
  70885. }
  70886. // load the reset of the header in native 32 bit int
  70887. var header = new Int32Array(this.arrayBuffer, 12, 13);
  70888. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  70889. var oppositeEndianess = header[0] === 0x01020304;
  70890. // read all the header elements in order they exist in the file, without modification (sans endainness)
  70891. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  70892. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  70893. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  70894. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  70895. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  70896. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  70897. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  70898. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  70899. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  70900. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  70901. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  70902. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  70903. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  70904. if (this.glType !== 0) {
  70905. BABYLON.Tools.Error("only compressed formats currently supported");
  70906. return;
  70907. }
  70908. else {
  70909. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  70910. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  70911. }
  70912. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  70913. BABYLON.Tools.Error("only 2D textures currently supported");
  70914. return;
  70915. }
  70916. if (this.numberOfArrayElements !== 0) {
  70917. BABYLON.Tools.Error("texture arrays not currently supported");
  70918. return;
  70919. }
  70920. if (this.numberOfFaces !== facesExpected) {
  70921. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  70922. return;
  70923. }
  70924. // we now have a completely validated file, so could use existence of loadType as success
  70925. // would need to make this more elaborate & adjust checks above to support more than one load type
  70926. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  70927. }
  70928. // not as fast hardware based, but will probably never need to use
  70929. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  70930. return ((val & 0xFF) << 24)
  70931. | ((val & 0xFF00) << 8)
  70932. | ((val >> 8) & 0xFF00)
  70933. | ((val >> 24) & 0xFF);
  70934. };
  70935. /**
  70936. * It is assumed that the texture has already been created & is currently bound
  70937. */
  70938. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  70939. switch (this.loadType) {
  70940. case KhronosTextureContainer.COMPRESSED_2D:
  70941. this._upload2DCompressedLevels(gl, loadMipmaps);
  70942. break;
  70943. case KhronosTextureContainer.TEX_2D:
  70944. case KhronosTextureContainer.COMPRESSED_3D:
  70945. case KhronosTextureContainer.TEX_3D:
  70946. }
  70947. };
  70948. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  70949. // initialize width & height for level 1
  70950. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  70951. var width = this.pixelWidth;
  70952. var height = this.pixelHeight;
  70953. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  70954. for (var level = 0; level < mipmapCount; level++) {
  70955. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  70956. for (var face = 0; face < this.numberOfFaces; face++) {
  70957. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  70958. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  70959. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  70960. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  70961. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  70962. }
  70963. width = Math.max(1.0, width * 0.5);
  70964. height = Math.max(1.0, height * 0.5);
  70965. }
  70966. };
  70967. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  70968. // load types
  70969. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  70970. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  70971. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  70972. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  70973. return KhronosTextureContainer;
  70974. }());
  70975. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  70976. })(BABYLON || (BABYLON = {}));
  70977. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  70978. var BABYLON;
  70979. (function (BABYLON) {
  70980. var Debug = /** @class */ (function () {
  70981. function Debug() {
  70982. }
  70983. Debug.AxesViewer = /** @class */ (function () {
  70984. function AxesViewer(scene, scaleLines) {
  70985. if (scaleLines === void 0) { scaleLines = 1; }
  70986. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70987. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70988. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70989. this.scaleLines = 1;
  70990. this.scaleLines = scaleLines;
  70991. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  70992. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  70993. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  70994. this._xmesh.renderingGroupId = 2;
  70995. this._ymesh.renderingGroupId = 2;
  70996. this._zmesh.renderingGroupId = 2;
  70997. this._xmesh.material.checkReadyOnlyOnce = true;
  70998. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  70999. this._ymesh.material.checkReadyOnlyOnce = true;
  71000. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  71001. this._zmesh.material.checkReadyOnlyOnce = true;
  71002. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  71003. this.scene = scene;
  71004. }
  71005. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  71006. var scaleLines = this.scaleLines;
  71007. if (this._xmesh) {
  71008. this._xmesh.position.copyFrom(position);
  71009. }
  71010. if (this._ymesh) {
  71011. this._ymesh.position.copyFrom(position);
  71012. }
  71013. if (this._zmesh) {
  71014. this._zmesh.position.copyFrom(position);
  71015. }
  71016. var point2 = this._xline[1];
  71017. point2.x = xaxis.x * scaleLines;
  71018. point2.y = xaxis.y * scaleLines;
  71019. point2.z = xaxis.z * scaleLines;
  71020. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  71021. point2 = this._yline[1];
  71022. point2.x = yaxis.x * scaleLines;
  71023. point2.y = yaxis.y * scaleLines;
  71024. point2.z = yaxis.z * scaleLines;
  71025. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  71026. point2 = this._zline[1];
  71027. point2.x = zaxis.x * scaleLines;
  71028. point2.y = zaxis.y * scaleLines;
  71029. point2.z = zaxis.z * scaleLines;
  71030. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  71031. };
  71032. AxesViewer.prototype.dispose = function () {
  71033. if (this._xmesh) {
  71034. this._xmesh.dispose();
  71035. }
  71036. if (this._ymesh) {
  71037. this._ymesh.dispose();
  71038. }
  71039. if (this._zmesh) {
  71040. this._zmesh.dispose();
  71041. }
  71042. this._xmesh = null;
  71043. this._ymesh = null;
  71044. this._zmesh = null;
  71045. this.scene = null;
  71046. };
  71047. return AxesViewer;
  71048. }());
  71049. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  71050. __extends(BoneAxesViewer, _super);
  71051. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  71052. if (scaleLines === void 0) { scaleLines = 1; }
  71053. var _this = _super.call(this, scene, scaleLines) || this;
  71054. _this.pos = BABYLON.Vector3.Zero();
  71055. _this.xaxis = BABYLON.Vector3.Zero();
  71056. _this.yaxis = BABYLON.Vector3.Zero();
  71057. _this.zaxis = BABYLON.Vector3.Zero();
  71058. _this.mesh = mesh;
  71059. _this.bone = bone;
  71060. return _this;
  71061. }
  71062. BoneAxesViewer.prototype.update = function () {
  71063. if (!this.mesh || !this.bone) {
  71064. return;
  71065. }
  71066. var bone = this.bone;
  71067. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  71068. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  71069. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  71070. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  71071. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  71072. };
  71073. BoneAxesViewer.prototype.dispose = function () {
  71074. if (this.mesh) {
  71075. this.mesh = null;
  71076. this.bone = null;
  71077. _super.prototype.dispose.call(this);
  71078. }
  71079. };
  71080. return BoneAxesViewer;
  71081. }(Debug.AxesViewer));
  71082. Debug.PhysicsViewer = /** @class */ (function () {
  71083. function PhysicsViewer(scene) {
  71084. this._impostors = [];
  71085. this._meshes = [];
  71086. this._numMeshes = 0;
  71087. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71088. var physicEngine = this._scene.getPhysicsEngine();
  71089. if (physicEngine) {
  71090. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  71091. }
  71092. }
  71093. PhysicsViewer.prototype._updateDebugMeshes = function () {
  71094. var plugin = this._physicsEnginePlugin;
  71095. for (var i = 0; i < this._numMeshes; i++) {
  71096. var impostor = this._impostors[i];
  71097. if (!impostor) {
  71098. continue;
  71099. }
  71100. if (impostor.isDisposed) {
  71101. this.hideImpostor(this._impostors[i--]);
  71102. }
  71103. else {
  71104. var mesh = this._meshes[i];
  71105. if (mesh && plugin) {
  71106. plugin.syncMeshWithImpostor(mesh, impostor);
  71107. }
  71108. }
  71109. }
  71110. };
  71111. PhysicsViewer.prototype.showImpostor = function (impostor) {
  71112. if (!this._scene) {
  71113. return;
  71114. }
  71115. for (var i = 0; i < this._numMeshes; i++) {
  71116. if (this._impostors[i] == impostor) {
  71117. return;
  71118. }
  71119. }
  71120. var debugMesh = this._getDebugMesh(impostor, this._scene);
  71121. if (debugMesh) {
  71122. this._impostors[this._numMeshes] = impostor;
  71123. this._meshes[this._numMeshes] = debugMesh;
  71124. if (this._numMeshes === 0) {
  71125. this._renderFunction = this._updateDebugMeshes.bind(this);
  71126. this._scene.registerBeforeRender(this._renderFunction);
  71127. }
  71128. this._numMeshes++;
  71129. }
  71130. };
  71131. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  71132. if (!impostor || !this._scene) {
  71133. return;
  71134. }
  71135. var removed = false;
  71136. for (var i = 0; i < this._numMeshes; i++) {
  71137. if (this._impostors[i] == impostor) {
  71138. var mesh = this._meshes[i];
  71139. if (!mesh) {
  71140. continue;
  71141. }
  71142. this._scene.removeMesh(mesh);
  71143. mesh.dispose();
  71144. this._numMeshes--;
  71145. if (this._numMeshes > 0) {
  71146. this._meshes[i] = this._meshes[this._numMeshes];
  71147. this._impostors[i] = this._impostors[this._numMeshes];
  71148. this._meshes[this._numMeshes] = null;
  71149. this._impostors[this._numMeshes] = null;
  71150. }
  71151. else {
  71152. this._meshes[0] = null;
  71153. this._impostors[0] = null;
  71154. }
  71155. removed = true;
  71156. break;
  71157. }
  71158. }
  71159. if (removed && this._numMeshes === 0) {
  71160. this._scene.unregisterBeforeRender(this._renderFunction);
  71161. }
  71162. };
  71163. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  71164. if (!this._debugMaterial) {
  71165. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  71166. this._debugMaterial.wireframe = true;
  71167. }
  71168. return this._debugMaterial;
  71169. };
  71170. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  71171. if (!this._debugBoxMesh) {
  71172. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  71173. this._debugBoxMesh.renderingGroupId = 1;
  71174. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  71175. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  71176. scene.removeMesh(this._debugBoxMesh);
  71177. }
  71178. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  71179. };
  71180. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  71181. if (!this._debugSphereMesh) {
  71182. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  71183. this._debugSphereMesh.renderingGroupId = 1;
  71184. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  71185. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  71186. scene.removeMesh(this._debugSphereMesh);
  71187. }
  71188. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  71189. };
  71190. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  71191. var mesh = null;
  71192. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  71193. mesh = this._getDebugBoxMesh(scene);
  71194. impostor.getBoxSizeToRef(mesh.scaling);
  71195. }
  71196. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  71197. mesh = this._getDebugSphereMesh(scene);
  71198. var radius = impostor.getRadius();
  71199. mesh.scaling.x = radius * 2;
  71200. mesh.scaling.y = radius * 2;
  71201. mesh.scaling.z = radius * 2;
  71202. }
  71203. return mesh;
  71204. };
  71205. PhysicsViewer.prototype.dispose = function () {
  71206. for (var i = 0; i < this._numMeshes; i++) {
  71207. this.hideImpostor(this._impostors[i]);
  71208. }
  71209. if (this._debugBoxMesh) {
  71210. this._debugBoxMesh.dispose();
  71211. }
  71212. if (this._debugSphereMesh) {
  71213. this._debugSphereMesh.dispose();
  71214. }
  71215. if (this._debugMaterial) {
  71216. this._debugMaterial.dispose();
  71217. }
  71218. this._impostors.length = 0;
  71219. this._scene = null;
  71220. this._physicsEnginePlugin = null;
  71221. };
  71222. return PhysicsViewer;
  71223. }());
  71224. Debug.SkeletonViewer = /** @class */ (function () {
  71225. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  71226. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  71227. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  71228. this.skeleton = skeleton;
  71229. this.mesh = mesh;
  71230. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  71231. this.renderingGroupId = renderingGroupId;
  71232. this.color = BABYLON.Color3.White();
  71233. this._debugLines = new Array();
  71234. this._isEnabled = false;
  71235. this._scene = scene;
  71236. this.update();
  71237. this._renderFunction = this.update.bind(this);
  71238. }
  71239. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  71240. get: function () {
  71241. return this._isEnabled;
  71242. },
  71243. set: function (value) {
  71244. if (this._isEnabled === value) {
  71245. return;
  71246. }
  71247. this._isEnabled = value;
  71248. if (value) {
  71249. this._scene.registerBeforeRender(this._renderFunction);
  71250. }
  71251. else {
  71252. this._scene.unregisterBeforeRender(this._renderFunction);
  71253. }
  71254. },
  71255. enumerable: true,
  71256. configurable: true
  71257. });
  71258. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  71259. if (x === void 0) { x = 0; }
  71260. if (y === void 0) { y = 0; }
  71261. if (z === void 0) { z = 0; }
  71262. var tmat = BABYLON.Tmp.Matrix[0];
  71263. var parentBone = bone.getParent();
  71264. tmat.copyFrom(bone.getLocalMatrix());
  71265. if (x !== 0 || y !== 0 || z !== 0) {
  71266. var tmat2 = BABYLON.Tmp.Matrix[1];
  71267. BABYLON.Matrix.IdentityToRef(tmat2);
  71268. tmat2.m[12] = x;
  71269. tmat2.m[13] = y;
  71270. tmat2.m[14] = z;
  71271. tmat2.multiplyToRef(tmat, tmat);
  71272. }
  71273. if (parentBone) {
  71274. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  71275. }
  71276. tmat.multiplyToRef(meshMat, tmat);
  71277. position.x = tmat.m[12];
  71278. position.y = tmat.m[13];
  71279. position.z = tmat.m[14];
  71280. };
  71281. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  71282. var len = bones.length;
  71283. var meshPos = this.mesh.position;
  71284. for (var i = 0; i < len; i++) {
  71285. var bone = bones[i];
  71286. var points = this._debugLines[i];
  71287. if (!points) {
  71288. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71289. this._debugLines[i] = points;
  71290. }
  71291. this._getBonePosition(points[0], bone, meshMat);
  71292. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  71293. points[0].subtractInPlace(meshPos);
  71294. points[1].subtractInPlace(meshPos);
  71295. }
  71296. };
  71297. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  71298. var len = bones.length;
  71299. var boneNum = 0;
  71300. var meshPos = this.mesh.position;
  71301. for (var i = len - 1; i >= 0; i--) {
  71302. var childBone = bones[i];
  71303. var parentBone = childBone.getParent();
  71304. if (!parentBone) {
  71305. continue;
  71306. }
  71307. var points = this._debugLines[boneNum];
  71308. if (!points) {
  71309. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71310. this._debugLines[boneNum] = points;
  71311. }
  71312. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  71313. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  71314. points[0].subtractInPlace(meshPos);
  71315. points[1].subtractInPlace(meshPos);
  71316. boneNum++;
  71317. }
  71318. };
  71319. SkeletonViewer.prototype.update = function () {
  71320. if (this.autoUpdateBonesMatrices) {
  71321. this.skeleton.computeAbsoluteTransforms();
  71322. }
  71323. if (this.skeleton.bones[0].length === undefined) {
  71324. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  71325. }
  71326. else {
  71327. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  71328. }
  71329. if (!this._debugMesh) {
  71330. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  71331. this._debugMesh.renderingGroupId = this.renderingGroupId;
  71332. }
  71333. else {
  71334. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  71335. }
  71336. this._debugMesh.position.copyFrom(this.mesh.position);
  71337. this._debugMesh.color = this.color;
  71338. };
  71339. SkeletonViewer.prototype.dispose = function () {
  71340. if (this._debugMesh) {
  71341. this.isEnabled = false;
  71342. this._debugMesh.dispose();
  71343. this._debugMesh = null;
  71344. }
  71345. };
  71346. return SkeletonViewer;
  71347. }());
  71348. return Debug;
  71349. }());
  71350. BABYLON.Debug = Debug;
  71351. })(BABYLON || (BABYLON = {}));
  71352. //# sourceMappingURL=babylon.debugModules.js.map
  71353. var BABYLON;
  71354. (function (BABYLON) {
  71355. var RayHelper = /** @class */ (function () {
  71356. function RayHelper(ray) {
  71357. this.ray = ray;
  71358. }
  71359. RayHelper.CreateAndShow = function (ray, scene, color) {
  71360. var helper = new RayHelper(ray);
  71361. helper.show(scene, color);
  71362. return helper;
  71363. };
  71364. RayHelper.prototype.show = function (scene, color) {
  71365. if (!this._renderFunction && this.ray) {
  71366. var ray = this.ray;
  71367. this._renderFunction = this._render.bind(this);
  71368. this._scene = scene;
  71369. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  71370. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  71371. if (this._renderFunction) {
  71372. this._scene.registerBeforeRender(this._renderFunction);
  71373. }
  71374. }
  71375. if (color && this._renderLine) {
  71376. this._renderLine.color.copyFrom(color);
  71377. }
  71378. };
  71379. RayHelper.prototype.hide = function () {
  71380. if (this._renderFunction && this._scene) {
  71381. this._scene.unregisterBeforeRender(this._renderFunction);
  71382. this._scene = null;
  71383. this._renderFunction = null;
  71384. if (this._renderLine) {
  71385. this._renderLine.dispose();
  71386. this._renderLine = null;
  71387. }
  71388. this._renderPoints = [];
  71389. }
  71390. };
  71391. RayHelper.prototype._render = function () {
  71392. var ray = this.ray;
  71393. if (!ray) {
  71394. return;
  71395. }
  71396. var point = this._renderPoints[1];
  71397. var len = Math.min(ray.length, 1000000);
  71398. point.copyFrom(ray.direction);
  71399. point.scaleInPlace(len);
  71400. point.addInPlace(ray.origin);
  71401. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  71402. };
  71403. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  71404. this._attachedToMesh = mesh;
  71405. var ray = this.ray;
  71406. if (!ray) {
  71407. return;
  71408. }
  71409. if (!ray.direction) {
  71410. ray.direction = BABYLON.Vector3.Zero();
  71411. }
  71412. if (!ray.origin) {
  71413. ray.origin = BABYLON.Vector3.Zero();
  71414. }
  71415. if (length) {
  71416. ray.length = length;
  71417. }
  71418. if (!meshSpaceOrigin) {
  71419. meshSpaceOrigin = BABYLON.Vector3.Zero();
  71420. }
  71421. if (!meshSpaceDirection) {
  71422. // -1 so that this will work with Mesh.lookAt
  71423. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  71424. }
  71425. if (!this._meshSpaceDirection) {
  71426. this._meshSpaceDirection = meshSpaceDirection.clone();
  71427. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  71428. }
  71429. else {
  71430. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  71431. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  71432. }
  71433. if (!this._updateToMeshFunction) {
  71434. this._updateToMeshFunction = this._updateToMesh.bind(this);
  71435. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  71436. }
  71437. this._updateToMesh();
  71438. };
  71439. RayHelper.prototype.detachFromMesh = function () {
  71440. if (this._attachedToMesh) {
  71441. if (this._updateToMeshFunction) {
  71442. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  71443. }
  71444. this._attachedToMesh = null;
  71445. this._updateToMeshFunction = null;
  71446. }
  71447. };
  71448. RayHelper.prototype._updateToMesh = function () {
  71449. var ray = this.ray;
  71450. if (!this._attachedToMesh || !ray) {
  71451. return;
  71452. }
  71453. if (this._attachedToMesh._isDisposed) {
  71454. this.detachFromMesh();
  71455. return;
  71456. }
  71457. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  71458. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  71459. };
  71460. RayHelper.prototype.dispose = function () {
  71461. this.hide();
  71462. this.detachFromMesh();
  71463. this.ray = null;
  71464. };
  71465. return RayHelper;
  71466. }());
  71467. BABYLON.RayHelper = RayHelper;
  71468. })(BABYLON || (BABYLON = {}));
  71469. //# sourceMappingURL=babylon.rayHelper.js.map
  71470. var BABYLON;
  71471. (function (BABYLON) {
  71472. // load the inspector using require, if not present in the global namespace.
  71473. var DebugLayer = /** @class */ (function () {
  71474. function DebugLayer(scene) {
  71475. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  71476. this._scene = scene;
  71477. // load inspector using require, if it doesn't exist on the global namespace.
  71478. }
  71479. /** Creates the inspector window. */
  71480. DebugLayer.prototype._createInspector = function (config) {
  71481. if (config === void 0) { config = {}; }
  71482. var popup = config.popup || false;
  71483. var initialTab = config.initialTab || 0;
  71484. var parentElement = config.parentElement || null;
  71485. if (!this._inspector) {
  71486. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  71487. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  71488. } // else nothing to do,; instance is already existing
  71489. };
  71490. DebugLayer.prototype.isVisible = function () {
  71491. if (!this._inspector) {
  71492. return false;
  71493. }
  71494. return true;
  71495. };
  71496. DebugLayer.prototype.hide = function () {
  71497. if (this._inspector) {
  71498. try {
  71499. this._inspector.dispose();
  71500. }
  71501. catch (e) {
  71502. // If the inspector has been removed directly from the inspector tool
  71503. }
  71504. this._inspector = null;
  71505. }
  71506. };
  71507. DebugLayer.prototype.show = function (config) {
  71508. if (config === void 0) { config = {}; }
  71509. if (typeof this.BJSINSPECTOR == 'undefined') {
  71510. // Load inspector and add it to the DOM
  71511. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  71512. }
  71513. else {
  71514. // Otherwise creates the inspector
  71515. this._createInspector(config);
  71516. }
  71517. };
  71518. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  71519. return DebugLayer;
  71520. }());
  71521. BABYLON.DebugLayer = DebugLayer;
  71522. })(BABYLON || (BABYLON = {}));
  71523. //# sourceMappingURL=babylon.debugLayer.js.map
  71524. var BABYLON;
  71525. (function (BABYLON) {
  71526. var BoundingBoxRenderer = /** @class */ (function () {
  71527. function BoundingBoxRenderer(scene) {
  71528. this.frontColor = new BABYLON.Color3(1, 1, 1);
  71529. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  71530. this.showBackLines = true;
  71531. this.renderList = new BABYLON.SmartArray(32);
  71532. this._vertexBuffers = {};
  71533. this._scene = scene;
  71534. }
  71535. BoundingBoxRenderer.prototype._prepareRessources = function () {
  71536. if (this._colorShader) {
  71537. return;
  71538. }
  71539. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  71540. attributes: [BABYLON.VertexBuffer.PositionKind],
  71541. uniforms: ["world", "viewProjection", "color"]
  71542. });
  71543. var engine = this._scene.getEngine();
  71544. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  71545. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  71546. this._createIndexBuffer();
  71547. };
  71548. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  71549. var engine = this._scene.getEngine();
  71550. 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]);
  71551. };
  71552. BoundingBoxRenderer.prototype._rebuild = function () {
  71553. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71554. if (vb) {
  71555. vb._rebuild();
  71556. }
  71557. this._createIndexBuffer();
  71558. };
  71559. BoundingBoxRenderer.prototype.reset = function () {
  71560. this.renderList.reset();
  71561. };
  71562. BoundingBoxRenderer.prototype.render = function () {
  71563. if (this.renderList.length === 0) {
  71564. return;
  71565. }
  71566. this._prepareRessources();
  71567. if (!this._colorShader.isReady()) {
  71568. return;
  71569. }
  71570. var engine = this._scene.getEngine();
  71571. engine.setDepthWrite(false);
  71572. this._colorShader._preBind();
  71573. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  71574. var boundingBox = this.renderList.data[boundingBoxIndex];
  71575. var min = boundingBox.minimum;
  71576. var max = boundingBox.maximum;
  71577. var diff = max.subtract(min);
  71578. var median = min.add(diff.scale(0.5));
  71579. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  71580. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  71581. .multiply(boundingBox.getWorldMatrix());
  71582. // VBOs
  71583. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  71584. if (this.showBackLines) {
  71585. // Back
  71586. engine.setDepthFunctionToGreaterOrEqual();
  71587. this._scene.resetCachedMaterial();
  71588. this._colorShader.setColor4("color", this.backColor.toColor4());
  71589. this._colorShader.bind(worldMatrix);
  71590. // Draw order
  71591. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  71592. }
  71593. // Front
  71594. engine.setDepthFunctionToLess();
  71595. this._scene.resetCachedMaterial();
  71596. this._colorShader.setColor4("color", this.frontColor.toColor4());
  71597. this._colorShader.bind(worldMatrix);
  71598. // Draw order
  71599. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  71600. }
  71601. this._colorShader.unbind();
  71602. engine.setDepthFunctionToLessOrEqual();
  71603. engine.setDepthWrite(true);
  71604. };
  71605. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  71606. this._prepareRessources();
  71607. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  71608. return;
  71609. }
  71610. var engine = this._scene.getEngine();
  71611. engine.setDepthWrite(false);
  71612. engine.setColorWrite(false);
  71613. this._colorShader._preBind();
  71614. var boundingBox = mesh._boundingInfo.boundingBox;
  71615. var min = boundingBox.minimum;
  71616. var max = boundingBox.maximum;
  71617. var diff = max.subtract(min);
  71618. var median = min.add(diff.scale(0.5));
  71619. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  71620. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  71621. .multiply(boundingBox.getWorldMatrix());
  71622. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  71623. engine.setDepthFunctionToLess();
  71624. this._scene.resetCachedMaterial();
  71625. this._colorShader.bind(worldMatrix);
  71626. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 24);
  71627. this._colorShader.unbind();
  71628. engine.setDepthFunctionToLessOrEqual();
  71629. engine.setDepthWrite(true);
  71630. engine.setColorWrite(true);
  71631. };
  71632. BoundingBoxRenderer.prototype.dispose = function () {
  71633. if (!this._colorShader) {
  71634. return;
  71635. }
  71636. this.renderList.dispose();
  71637. this._colorShader.dispose();
  71638. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71639. if (buffer) {
  71640. buffer.dispose();
  71641. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71642. }
  71643. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71644. };
  71645. return BoundingBoxRenderer;
  71646. }());
  71647. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  71648. })(BABYLON || (BABYLON = {}));
  71649. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  71650. var BABYLON;
  71651. (function (BABYLON) {
  71652. var MorphTarget = /** @class */ (function () {
  71653. function MorphTarget(name, influence) {
  71654. if (influence === void 0) { influence = 0; }
  71655. this.name = name;
  71656. this.animations = new Array();
  71657. this._positions = null;
  71658. this._normals = null;
  71659. this._tangents = null;
  71660. this.onInfluenceChanged = new BABYLON.Observable();
  71661. this.influence = influence;
  71662. }
  71663. Object.defineProperty(MorphTarget.prototype, "influence", {
  71664. get: function () {
  71665. return this._influence;
  71666. },
  71667. set: function (influence) {
  71668. if (this._influence === influence) {
  71669. return;
  71670. }
  71671. var previous = this._influence;
  71672. this._influence = influence;
  71673. if (this.onInfluenceChanged.hasObservers) {
  71674. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  71675. }
  71676. },
  71677. enumerable: true,
  71678. configurable: true
  71679. });
  71680. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  71681. get: function () {
  71682. return !!this._positions;
  71683. },
  71684. enumerable: true,
  71685. configurable: true
  71686. });
  71687. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  71688. get: function () {
  71689. return !!this._normals;
  71690. },
  71691. enumerable: true,
  71692. configurable: true
  71693. });
  71694. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  71695. get: function () {
  71696. return !!this._tangents;
  71697. },
  71698. enumerable: true,
  71699. configurable: true
  71700. });
  71701. MorphTarget.prototype.setPositions = function (data) {
  71702. this._positions = data;
  71703. };
  71704. MorphTarget.prototype.getPositions = function () {
  71705. return this._positions;
  71706. };
  71707. MorphTarget.prototype.setNormals = function (data) {
  71708. this._normals = data;
  71709. };
  71710. MorphTarget.prototype.getNormals = function () {
  71711. return this._normals;
  71712. };
  71713. MorphTarget.prototype.setTangents = function (data) {
  71714. this._tangents = data;
  71715. };
  71716. MorphTarget.prototype.getTangents = function () {
  71717. return this._tangents;
  71718. };
  71719. /**
  71720. * Serializes the current target into a Serialization object.
  71721. * Returns the serialized object.
  71722. */
  71723. MorphTarget.prototype.serialize = function () {
  71724. var serializationObject = {};
  71725. serializationObject.name = this.name;
  71726. serializationObject.influence = this.influence;
  71727. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  71728. if (this.hasNormals) {
  71729. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  71730. }
  71731. if (this.hasTangents) {
  71732. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  71733. }
  71734. // Animations
  71735. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  71736. return serializationObject;
  71737. };
  71738. // Statics
  71739. MorphTarget.Parse = function (serializationObject) {
  71740. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  71741. result.setPositions(serializationObject.positions);
  71742. if (serializationObject.normals) {
  71743. result.setNormals(serializationObject.normals);
  71744. }
  71745. if (serializationObject.tangents) {
  71746. result.setTangents(serializationObject.tangents);
  71747. }
  71748. // Animations
  71749. if (serializationObject.animations) {
  71750. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  71751. var parsedAnimation = serializationObject.animations[animationIndex];
  71752. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  71753. }
  71754. }
  71755. return result;
  71756. };
  71757. MorphTarget.FromMesh = function (mesh, name, influence) {
  71758. if (!name) {
  71759. name = mesh.name;
  71760. }
  71761. var result = new MorphTarget(name, influence);
  71762. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  71763. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  71764. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  71765. }
  71766. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  71767. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  71768. }
  71769. return result;
  71770. };
  71771. return MorphTarget;
  71772. }());
  71773. BABYLON.MorphTarget = MorphTarget;
  71774. })(BABYLON || (BABYLON = {}));
  71775. //# sourceMappingURL=babylon.morphTarget.js.map
  71776. var BABYLON;
  71777. (function (BABYLON) {
  71778. var MorphTargetManager = /** @class */ (function () {
  71779. function MorphTargetManager(scene) {
  71780. if (scene === void 0) { scene = null; }
  71781. this._targets = new Array();
  71782. this._targetObservable = new Array();
  71783. this._activeTargets = new BABYLON.SmartArray(16);
  71784. this._supportsNormals = false;
  71785. this._supportsTangents = false;
  71786. this._vertexCount = 0;
  71787. this._uniqueId = 0;
  71788. this._tempInfluences = new Array();
  71789. if (!scene) {
  71790. scene = BABYLON.Engine.LastCreatedScene;
  71791. }
  71792. this._scene = scene;
  71793. if (this._scene) {
  71794. this._scene.morphTargetManagers.push(this);
  71795. this._uniqueId = this._scene.getUniqueId();
  71796. }
  71797. }
  71798. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  71799. get: function () {
  71800. return this._uniqueId;
  71801. },
  71802. enumerable: true,
  71803. configurable: true
  71804. });
  71805. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  71806. get: function () {
  71807. return this._vertexCount;
  71808. },
  71809. enumerable: true,
  71810. configurable: true
  71811. });
  71812. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  71813. get: function () {
  71814. return this._supportsNormals;
  71815. },
  71816. enumerable: true,
  71817. configurable: true
  71818. });
  71819. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  71820. get: function () {
  71821. return this._supportsTangents;
  71822. },
  71823. enumerable: true,
  71824. configurable: true
  71825. });
  71826. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  71827. get: function () {
  71828. return this._targets.length;
  71829. },
  71830. enumerable: true,
  71831. configurable: true
  71832. });
  71833. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  71834. get: function () {
  71835. return this._activeTargets.length;
  71836. },
  71837. enumerable: true,
  71838. configurable: true
  71839. });
  71840. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  71841. get: function () {
  71842. return this._influences;
  71843. },
  71844. enumerable: true,
  71845. configurable: true
  71846. });
  71847. MorphTargetManager.prototype.getActiveTarget = function (index) {
  71848. return this._activeTargets.data[index];
  71849. };
  71850. MorphTargetManager.prototype.getTarget = function (index) {
  71851. return this._targets[index];
  71852. };
  71853. MorphTargetManager.prototype.addTarget = function (target) {
  71854. var _this = this;
  71855. this._targets.push(target);
  71856. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  71857. _this._syncActiveTargets(needUpdate);
  71858. }));
  71859. this._syncActiveTargets(true);
  71860. };
  71861. MorphTargetManager.prototype.removeTarget = function (target) {
  71862. var index = this._targets.indexOf(target);
  71863. if (index >= 0) {
  71864. this._targets.splice(index, 1);
  71865. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  71866. this._syncActiveTargets(true);
  71867. }
  71868. };
  71869. /**
  71870. * Serializes the current manager into a Serialization object.
  71871. * Returns the serialized object.
  71872. */
  71873. MorphTargetManager.prototype.serialize = function () {
  71874. var serializationObject = {};
  71875. serializationObject.id = this.uniqueId;
  71876. serializationObject.targets = [];
  71877. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  71878. var target = _a[_i];
  71879. serializationObject.targets.push(target.serialize());
  71880. }
  71881. return serializationObject;
  71882. };
  71883. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  71884. var influenceCount = 0;
  71885. this._activeTargets.reset();
  71886. this._supportsNormals = true;
  71887. this._supportsTangents = true;
  71888. this._vertexCount = 0;
  71889. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  71890. var target = _a[_i];
  71891. this._activeTargets.push(target);
  71892. this._tempInfluences[influenceCount++] = target.influence;
  71893. var positions = target.getPositions();
  71894. if (positions) {
  71895. this._supportsNormals = this._supportsNormals && target.hasNormals;
  71896. this._supportsTangents = this._supportsTangents && target.hasTangents;
  71897. var vertexCount = positions.length / 3;
  71898. if (this._vertexCount === 0) {
  71899. this._vertexCount = vertexCount;
  71900. }
  71901. else if (this._vertexCount !== vertexCount) {
  71902. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  71903. return;
  71904. }
  71905. }
  71906. }
  71907. if (!this._influences || this._influences.length !== influenceCount) {
  71908. this._influences = new Float32Array(influenceCount);
  71909. }
  71910. for (var index = 0; index < influenceCount; index++) {
  71911. this._influences[index] = this._tempInfluences[index];
  71912. }
  71913. if (needUpdate && this._scene) {
  71914. // Flag meshes as dirty to resync with the active targets
  71915. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  71916. var mesh = _c[_b];
  71917. if (mesh.morphTargetManager === this) {
  71918. mesh._syncGeometryWithMorphTargetManager();
  71919. }
  71920. }
  71921. }
  71922. };
  71923. // Statics
  71924. MorphTargetManager.Parse = function (serializationObject, scene) {
  71925. var result = new MorphTargetManager(scene);
  71926. result._uniqueId = serializationObject.id;
  71927. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  71928. var targetData = _a[_i];
  71929. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  71930. }
  71931. return result;
  71932. };
  71933. return MorphTargetManager;
  71934. }());
  71935. BABYLON.MorphTargetManager = MorphTargetManager;
  71936. })(BABYLON || (BABYLON = {}));
  71937. //# sourceMappingURL=babylon.morphTargetManager.js.map
  71938. var BABYLON;
  71939. (function (BABYLON) {
  71940. var Octree = /** @class */ (function () {
  71941. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  71942. if (maxDepth === void 0) { maxDepth = 2; }
  71943. this.maxDepth = maxDepth;
  71944. this.dynamicContent = new Array();
  71945. this._maxBlockCapacity = maxBlockCapacity || 64;
  71946. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  71947. this._creationFunc = creationFunc;
  71948. }
  71949. // Methods
  71950. Octree.prototype.update = function (worldMin, worldMax, entries) {
  71951. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  71952. };
  71953. Octree.prototype.addMesh = function (entry) {
  71954. for (var index = 0; index < this.blocks.length; index++) {
  71955. var block = this.blocks[index];
  71956. block.addEntry(entry);
  71957. }
  71958. };
  71959. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  71960. this._selectionContent.reset();
  71961. for (var index = 0; index < this.blocks.length; index++) {
  71962. var block = this.blocks[index];
  71963. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  71964. }
  71965. if (allowDuplicate) {
  71966. this._selectionContent.concat(this.dynamicContent);
  71967. }
  71968. else {
  71969. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  71970. }
  71971. return this._selectionContent;
  71972. };
  71973. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  71974. this._selectionContent.reset();
  71975. for (var index = 0; index < this.blocks.length; index++) {
  71976. var block = this.blocks[index];
  71977. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  71978. }
  71979. if (allowDuplicate) {
  71980. this._selectionContent.concat(this.dynamicContent);
  71981. }
  71982. else {
  71983. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  71984. }
  71985. return this._selectionContent;
  71986. };
  71987. Octree.prototype.intersectsRay = function (ray) {
  71988. this._selectionContent.reset();
  71989. for (var index = 0; index < this.blocks.length; index++) {
  71990. var block = this.blocks[index];
  71991. block.intersectsRay(ray, this._selectionContent);
  71992. }
  71993. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  71994. return this._selectionContent;
  71995. };
  71996. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  71997. target.blocks = new Array();
  71998. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  71999. // Segmenting space
  72000. for (var x = 0; x < 2; x++) {
  72001. for (var y = 0; y < 2; y++) {
  72002. for (var z = 0; z < 2; z++) {
  72003. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  72004. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  72005. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  72006. block.addEntries(entries);
  72007. target.blocks.push(block);
  72008. }
  72009. }
  72010. }
  72011. };
  72012. Octree.CreationFuncForMeshes = function (entry, block) {
  72013. var boundingInfo = entry.getBoundingInfo();
  72014. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  72015. block.entries.push(entry);
  72016. }
  72017. };
  72018. Octree.CreationFuncForSubMeshes = function (entry, block) {
  72019. var boundingInfo = entry.getBoundingInfo();
  72020. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  72021. block.entries.push(entry);
  72022. }
  72023. };
  72024. return Octree;
  72025. }());
  72026. BABYLON.Octree = Octree;
  72027. })(BABYLON || (BABYLON = {}));
  72028. //# sourceMappingURL=babylon.octree.js.map
  72029. var BABYLON;
  72030. (function (BABYLON) {
  72031. var OctreeBlock = /** @class */ (function () {
  72032. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  72033. this.entries = new Array();
  72034. this._boundingVectors = new Array();
  72035. this._capacity = capacity;
  72036. this._depth = depth;
  72037. this._maxDepth = maxDepth;
  72038. this._creationFunc = creationFunc;
  72039. this._minPoint = minPoint;
  72040. this._maxPoint = maxPoint;
  72041. this._boundingVectors.push(minPoint.clone());
  72042. this._boundingVectors.push(maxPoint.clone());
  72043. this._boundingVectors.push(minPoint.clone());
  72044. this._boundingVectors[2].x = maxPoint.x;
  72045. this._boundingVectors.push(minPoint.clone());
  72046. this._boundingVectors[3].y = maxPoint.y;
  72047. this._boundingVectors.push(minPoint.clone());
  72048. this._boundingVectors[4].z = maxPoint.z;
  72049. this._boundingVectors.push(maxPoint.clone());
  72050. this._boundingVectors[5].z = minPoint.z;
  72051. this._boundingVectors.push(maxPoint.clone());
  72052. this._boundingVectors[6].x = minPoint.x;
  72053. this._boundingVectors.push(maxPoint.clone());
  72054. this._boundingVectors[7].y = minPoint.y;
  72055. }
  72056. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  72057. // Property
  72058. get: function () {
  72059. return this._capacity;
  72060. },
  72061. enumerable: true,
  72062. configurable: true
  72063. });
  72064. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  72065. get: function () {
  72066. return this._minPoint;
  72067. },
  72068. enumerable: true,
  72069. configurable: true
  72070. });
  72071. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  72072. get: function () {
  72073. return this._maxPoint;
  72074. },
  72075. enumerable: true,
  72076. configurable: true
  72077. });
  72078. // Methods
  72079. OctreeBlock.prototype.addEntry = function (entry) {
  72080. if (this.blocks) {
  72081. for (var index = 0; index < this.blocks.length; index++) {
  72082. var block = this.blocks[index];
  72083. block.addEntry(entry);
  72084. }
  72085. return;
  72086. }
  72087. this._creationFunc(entry, this);
  72088. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  72089. this.createInnerBlocks();
  72090. }
  72091. };
  72092. OctreeBlock.prototype.addEntries = function (entries) {
  72093. for (var index = 0; index < entries.length; index++) {
  72094. var mesh = entries[index];
  72095. this.addEntry(mesh);
  72096. }
  72097. };
  72098. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  72099. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  72100. if (this.blocks) {
  72101. for (var index = 0; index < this.blocks.length; index++) {
  72102. var block = this.blocks[index];
  72103. block.select(frustumPlanes, selection, allowDuplicate);
  72104. }
  72105. return;
  72106. }
  72107. if (allowDuplicate) {
  72108. selection.concat(this.entries);
  72109. }
  72110. else {
  72111. selection.concatWithNoDuplicate(this.entries);
  72112. }
  72113. }
  72114. };
  72115. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  72116. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  72117. if (this.blocks) {
  72118. for (var index = 0; index < this.blocks.length; index++) {
  72119. var block = this.blocks[index];
  72120. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  72121. }
  72122. return;
  72123. }
  72124. if (allowDuplicate) {
  72125. selection.concat(this.entries);
  72126. }
  72127. else {
  72128. selection.concatWithNoDuplicate(this.entries);
  72129. }
  72130. }
  72131. };
  72132. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  72133. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  72134. if (this.blocks) {
  72135. for (var index = 0; index < this.blocks.length; index++) {
  72136. var block = this.blocks[index];
  72137. block.intersectsRay(ray, selection);
  72138. }
  72139. return;
  72140. }
  72141. selection.concatWithNoDuplicate(this.entries);
  72142. }
  72143. };
  72144. OctreeBlock.prototype.createInnerBlocks = function () {
  72145. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  72146. };
  72147. return OctreeBlock;
  72148. }());
  72149. BABYLON.OctreeBlock = OctreeBlock;
  72150. })(BABYLON || (BABYLON = {}));
  72151. //# sourceMappingURL=babylon.octreeBlock.js.map
  72152. var BABYLON;
  72153. (function (BABYLON) {
  72154. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  72155. __extends(VRDistortionCorrectionPostProcess, _super);
  72156. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  72157. var _this = _super.call(this, name, "vrDistortionCorrection", [
  72158. 'LensCenter',
  72159. 'Scale',
  72160. 'ScaleIn',
  72161. 'HmdWarpParam'
  72162. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  72163. _this._isRightEye = isRightEye;
  72164. _this._distortionFactors = vrMetrics.distortionK;
  72165. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  72166. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  72167. _this.adaptScaleToCurrentViewport = true;
  72168. _this.onSizeChangedObservable.add(function () {
  72169. _this.aspectRatio = _this.width * .5 / _this.height;
  72170. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  72171. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  72172. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  72173. });
  72174. _this.onApplyObservable.add(function (effect) {
  72175. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  72176. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  72177. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  72178. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  72179. });
  72180. return _this;
  72181. }
  72182. return VRDistortionCorrectionPostProcess;
  72183. }(BABYLON.PostProcess));
  72184. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  72185. })(BABYLON || (BABYLON = {}));
  72186. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  72187. var BABYLON;
  72188. (function (BABYLON) {
  72189. var AnaglyphPostProcess = /** @class */ (function (_super) {
  72190. __extends(AnaglyphPostProcess, _super);
  72191. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  72192. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  72193. _this._passedProcess = rigCameras[0]._rigPostProcess;
  72194. _this.onApplyObservable.add(function (effect) {
  72195. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  72196. });
  72197. return _this;
  72198. }
  72199. return AnaglyphPostProcess;
  72200. }(BABYLON.PostProcess));
  72201. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  72202. })(BABYLON || (BABYLON = {}));
  72203. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  72204. var BABYLON;
  72205. (function (BABYLON) {
  72206. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  72207. __extends(StereoscopicInterlacePostProcess, _super);
  72208. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  72209. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  72210. _this._passedProcess = rigCameras[0]._rigPostProcess;
  72211. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  72212. _this.onSizeChangedObservable.add(function () {
  72213. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  72214. });
  72215. _this.onApplyObservable.add(function (effect) {
  72216. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  72217. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  72218. });
  72219. return _this;
  72220. }
  72221. return StereoscopicInterlacePostProcess;
  72222. }(BABYLON.PostProcess));
  72223. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  72224. })(BABYLON || (BABYLON = {}));
  72225. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  72226. var BABYLON;
  72227. (function (BABYLON) {
  72228. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  72229. function FreeCameraDeviceOrientationInput() {
  72230. var _this = this;
  72231. this._screenOrientationAngle = 0;
  72232. this._screenQuaternion = new BABYLON.Quaternion();
  72233. this._alpha = 0;
  72234. this._beta = 0;
  72235. this._gamma = 0;
  72236. this._orientationChanged = function () {
  72237. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  72238. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  72239. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  72240. };
  72241. this._deviceOrientation = function (evt) {
  72242. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  72243. _this._beta = evt.beta !== null ? evt.beta : 0;
  72244. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  72245. };
  72246. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  72247. this._orientationChanged();
  72248. }
  72249. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  72250. get: function () {
  72251. return this._camera;
  72252. },
  72253. set: function (camera) {
  72254. this._camera = camera;
  72255. if (this._camera != null && !this._camera.rotationQuaternion) {
  72256. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  72257. }
  72258. },
  72259. enumerable: true,
  72260. configurable: true
  72261. });
  72262. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  72263. window.addEventListener("orientationchange", this._orientationChanged);
  72264. window.addEventListener("deviceorientation", this._deviceOrientation);
  72265. //In certain cases, the attach control is called AFTER orientation was changed,
  72266. //So this is needed.
  72267. this._orientationChanged();
  72268. };
  72269. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  72270. window.removeEventListener("orientationchange", this._orientationChanged);
  72271. window.removeEventListener("deviceorientation", this._deviceOrientation);
  72272. };
  72273. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  72274. //if no device orientation provided, don't update the rotation.
  72275. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  72276. if (!this._alpha)
  72277. return;
  72278. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  72279. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  72280. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  72281. //Mirror on XY Plane
  72282. this._camera.rotationQuaternion.z *= -1;
  72283. this._camera.rotationQuaternion.w *= -1;
  72284. };
  72285. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  72286. return "FreeCameraDeviceOrientationInput";
  72287. };
  72288. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  72289. return "deviceOrientation";
  72290. };
  72291. return FreeCameraDeviceOrientationInput;
  72292. }());
  72293. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  72294. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  72295. })(BABYLON || (BABYLON = {}));
  72296. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  72297. var BABYLON;
  72298. (function (BABYLON) {
  72299. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  72300. function ArcRotateCameraVRDeviceOrientationInput() {
  72301. this.alphaCorrection = 1;
  72302. this.betaCorrection = 1;
  72303. this.gammaCorrection = 1;
  72304. this._alpha = 0;
  72305. this._gamma = 0;
  72306. this._dirty = false;
  72307. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  72308. }
  72309. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  72310. this.camera.attachControl(element, noPreventDefault);
  72311. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  72312. };
  72313. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  72314. if (evt.alpha !== null) {
  72315. this._alpha = +evt.alpha | 0;
  72316. }
  72317. if (evt.gamma !== null) {
  72318. this._gamma = +evt.gamma | 0;
  72319. }
  72320. this._dirty = true;
  72321. };
  72322. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  72323. if (this._dirty) {
  72324. this._dirty = false;
  72325. if (this._gamma < 0) {
  72326. this._gamma = 180 + this._gamma;
  72327. }
  72328. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  72329. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  72330. }
  72331. };
  72332. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  72333. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  72334. };
  72335. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  72336. return "ArcRotateCameraVRDeviceOrientationInput";
  72337. };
  72338. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  72339. return "VRDeviceOrientation";
  72340. };
  72341. return ArcRotateCameraVRDeviceOrientationInput;
  72342. }());
  72343. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  72344. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  72345. })(BABYLON || (BABYLON = {}));
  72346. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  72347. var BABYLON;
  72348. (function (BABYLON) {
  72349. var VRCameraMetrics = /** @class */ (function () {
  72350. function VRCameraMetrics() {
  72351. this.compensateDistortion = true;
  72352. }
  72353. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  72354. get: function () {
  72355. return this.hResolution / (2 * this.vResolution);
  72356. },
  72357. enumerable: true,
  72358. configurable: true
  72359. });
  72360. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  72361. get: function () {
  72362. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  72363. },
  72364. enumerable: true,
  72365. configurable: true
  72366. });
  72367. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  72368. get: function () {
  72369. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  72370. var h = (4 * meters) / this.hScreenSize;
  72371. return BABYLON.Matrix.Translation(h, 0, 0);
  72372. },
  72373. enumerable: true,
  72374. configurable: true
  72375. });
  72376. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  72377. get: function () {
  72378. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  72379. var h = (4 * meters) / this.hScreenSize;
  72380. return BABYLON.Matrix.Translation(-h, 0, 0);
  72381. },
  72382. enumerable: true,
  72383. configurable: true
  72384. });
  72385. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  72386. get: function () {
  72387. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  72388. },
  72389. enumerable: true,
  72390. configurable: true
  72391. });
  72392. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  72393. get: function () {
  72394. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  72395. },
  72396. enumerable: true,
  72397. configurable: true
  72398. });
  72399. VRCameraMetrics.GetDefault = function () {
  72400. var result = new VRCameraMetrics();
  72401. result.hResolution = 1280;
  72402. result.vResolution = 800;
  72403. result.hScreenSize = 0.149759993;
  72404. result.vScreenSize = 0.0935999975;
  72405. result.vScreenCenter = 0.0467999987;
  72406. result.eyeToScreenDistance = 0.0410000011;
  72407. result.lensSeparationDistance = 0.0635000020;
  72408. result.interpupillaryDistance = 0.0640000030;
  72409. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  72410. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  72411. result.postProcessScaleFactor = 1.714605507808412;
  72412. result.lensCenterOffset = 0.151976421;
  72413. return result;
  72414. };
  72415. return VRCameraMetrics;
  72416. }());
  72417. BABYLON.VRCameraMetrics = VRCameraMetrics;
  72418. })(BABYLON || (BABYLON = {}));
  72419. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  72420. var BABYLON;
  72421. (function (BABYLON) {
  72422. var WebVRFreeCamera = /** @class */ (function (_super) {
  72423. __extends(WebVRFreeCamera, _super);
  72424. function WebVRFreeCamera(name, position, scene, webVROptions) {
  72425. if (webVROptions === void 0) { webVROptions = {}; }
  72426. var _this = _super.call(this, name, position, scene) || this;
  72427. _this.webVROptions = webVROptions;
  72428. _this._vrDevice = null;
  72429. _this.rawPose = null;
  72430. _this._specsVersion = "1.1";
  72431. _this._attached = false;
  72432. _this._descendants = [];
  72433. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  72434. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  72435. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  72436. _this._standingMatrix = null;
  72437. // Represents device position and rotation in babylon space
  72438. _this.devicePosition = BABYLON.Vector3.Zero();
  72439. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  72440. _this.deviceScaleFactor = 1;
  72441. _this._deviceToWorld = BABYLON.Matrix.Identity();
  72442. _this._worldToDevice = BABYLON.Matrix.Identity();
  72443. _this.controllers = [];
  72444. _this.onControllersAttachedObservable = new BABYLON.Observable();
  72445. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  72446. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  72447. _this._defaultHeight = 0;
  72448. _this.deviceDistanceToRoomGround = function () {
  72449. if (_this._standingMatrix) {
  72450. // Add standing matrix offset to get real offset from ground in room
  72451. _this._standingMatrix.getTranslationToRef(_this._workingVector);
  72452. return _this._deviceRoomPosition.y + _this._workingVector.y;
  72453. }
  72454. else {
  72455. return _this._defaultHeight;
  72456. }
  72457. };
  72458. _this.useStandingMatrix = function (callback) {
  72459. if (callback === void 0) { callback = function (bool) { }; }
  72460. // Use standing matrix if availible
  72461. if (!navigator || !navigator.getVRDisplays) {
  72462. callback(false);
  72463. }
  72464. else {
  72465. navigator.getVRDisplays().then(function (displays) {
  72466. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  72467. callback(false);
  72468. }
  72469. else {
  72470. _this._standingMatrix = new BABYLON.Matrix();
  72471. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  72472. if (!_this.getScene().useRightHandedSystem) {
  72473. [2, 6, 8, 9, 14].forEach(function (num) {
  72474. if (_this._standingMatrix) {
  72475. _this._standingMatrix.m[num] *= -1;
  72476. }
  72477. });
  72478. }
  72479. callback(true);
  72480. }
  72481. });
  72482. }
  72483. };
  72484. _this._workingVector = BABYLON.Vector3.Zero();
  72485. _this._oneVector = BABYLON.Vector3.One();
  72486. _this._workingMatrix = BABYLON.Matrix.Identity();
  72487. _this._cache.position = BABYLON.Vector3.Zero();
  72488. if (webVROptions.defaultHeight) {
  72489. _this._defaultHeight = webVROptions.defaultHeight;
  72490. _this.position.y = _this._defaultHeight;
  72491. }
  72492. _this.minZ = 0.1;
  72493. //legacy support - the compensation boolean was removed.
  72494. if (arguments.length === 5) {
  72495. _this.webVROptions = arguments[4];
  72496. }
  72497. // default webVR options
  72498. if (_this.webVROptions.trackPosition == undefined) {
  72499. _this.webVROptions.trackPosition = true;
  72500. }
  72501. if (_this.webVROptions.controllerMeshes == undefined) {
  72502. _this.webVROptions.controllerMeshes = true;
  72503. }
  72504. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  72505. _this.webVROptions.defaultLightingOnControllers = true;
  72506. }
  72507. _this.rotationQuaternion = new BABYLON.Quaternion();
  72508. if (_this.webVROptions && _this.webVROptions.positionScale) {
  72509. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  72510. }
  72511. //enable VR
  72512. var engine = _this.getEngine();
  72513. _this._onVREnabled = function (success) { if (success) {
  72514. _this.initControllers();
  72515. } };
  72516. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  72517. engine.initWebVR().add(function (event) {
  72518. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  72519. return;
  72520. }
  72521. _this._vrDevice = event.vrDisplay;
  72522. //reset the rig parameters.
  72523. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  72524. if (_this._attached) {
  72525. _this.getEngine().enableVR();
  72526. }
  72527. });
  72528. if (typeof (VRFrameData) !== "undefined")
  72529. _this._frameData = new VRFrameData();
  72530. /**
  72531. * The idea behind the following lines:
  72532. * objects that have the camera as parent should actually have the rig cameras as a parent.
  72533. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  72534. * the second will not show it correctly.
  72535. *
  72536. * To solve this - each object that has the camera as parent will be added to a protected array.
  72537. * When the rig camera renders, it will take this array and set all of those to be its children.
  72538. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  72539. * Amazing!
  72540. */
  72541. scene.onBeforeCameraRenderObservable.add(function (camera) {
  72542. if (camera.parent === _this && _this.rigParenting) {
  72543. _this._descendants = _this.getDescendants(true, function (n) {
  72544. // don't take the cameras or the controllers!
  72545. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  72546. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  72547. return !isController && !isRigCamera;
  72548. });
  72549. _this._descendants.forEach(function (node) {
  72550. node.parent = camera;
  72551. });
  72552. }
  72553. });
  72554. scene.onAfterCameraRenderObservable.add(function (camera) {
  72555. if (camera.parent === _this && _this.rigParenting) {
  72556. _this._descendants.forEach(function (node) {
  72557. node.parent = _this;
  72558. });
  72559. }
  72560. });
  72561. return _this;
  72562. }
  72563. WebVRFreeCamera.prototype.dispose = function () {
  72564. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  72565. _super.prototype.dispose.call(this);
  72566. };
  72567. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  72568. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  72569. var gp = _a[_i];
  72570. if (gp.hand === name) {
  72571. return gp;
  72572. }
  72573. }
  72574. return null;
  72575. };
  72576. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  72577. get: function () {
  72578. if (!this._leftController) {
  72579. this._leftController = this.getControllerByName("left");
  72580. }
  72581. return this._leftController;
  72582. },
  72583. enumerable: true,
  72584. configurable: true
  72585. });
  72586. ;
  72587. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  72588. get: function () {
  72589. if (!this._rightController) {
  72590. this._rightController = this.getControllerByName("right");
  72591. }
  72592. return this._rightController;
  72593. },
  72594. enumerable: true,
  72595. configurable: true
  72596. });
  72597. ;
  72598. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  72599. if (length === void 0) { length = 100; }
  72600. if (this.leftCamera) {
  72601. // Use left eye to avoid computation to compute center on every call
  72602. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  72603. }
  72604. else {
  72605. return _super.prototype.getForwardRay.call(this, length);
  72606. }
  72607. };
  72608. WebVRFreeCamera.prototype._checkInputs = function () {
  72609. if (this._vrDevice && this._vrDevice.isPresenting) {
  72610. this._vrDevice.getFrameData(this._frameData);
  72611. this.updateFromDevice(this._frameData.pose);
  72612. }
  72613. _super.prototype._checkInputs.call(this);
  72614. };
  72615. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  72616. if (poseData && poseData.orientation) {
  72617. this.rawPose = poseData;
  72618. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  72619. if (this.getScene().useRightHandedSystem) {
  72620. this._deviceRoomRotationQuaternion.z *= -1;
  72621. this._deviceRoomRotationQuaternion.w *= -1;
  72622. }
  72623. if (this.webVROptions.trackPosition && this.rawPose.position) {
  72624. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  72625. if (this.getScene().useRightHandedSystem) {
  72626. this._deviceRoomPosition.z *= -1;
  72627. }
  72628. }
  72629. }
  72630. };
  72631. /**
  72632. * WebVR's attach control will start broadcasting frames to the device.
  72633. * Note that in certain browsers (chrome for example) this function must be called
  72634. * within a user-interaction callback. Example:
  72635. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  72636. *
  72637. * @param {HTMLElement} element
  72638. * @param {boolean} [noPreventDefault]
  72639. *
  72640. * @memberOf WebVRFreeCamera
  72641. */
  72642. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  72643. _super.prototype.attachControl.call(this, element, noPreventDefault);
  72644. this._attached = true;
  72645. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  72646. if (this._vrDevice) {
  72647. this.getEngine().enableVR();
  72648. }
  72649. };
  72650. WebVRFreeCamera.prototype.detachControl = function (element) {
  72651. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72652. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72653. _super.prototype.detachControl.call(this, element);
  72654. this._attached = false;
  72655. this.getEngine().disableVR();
  72656. };
  72657. WebVRFreeCamera.prototype.getClassName = function () {
  72658. return "WebVRFreeCamera";
  72659. };
  72660. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  72661. //uses the vrDisplay's "resetPose()".
  72662. //pitch and roll won't be affected.
  72663. this._vrDevice.resetPose();
  72664. };
  72665. WebVRFreeCamera.prototype._updateRigCameras = function () {
  72666. var camLeft = this._rigCameras[0];
  72667. var camRight = this._rigCameras[1];
  72668. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72669. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72670. camLeft.position.copyFrom(this._deviceRoomPosition);
  72671. camRight.position.copyFrom(this._deviceRoomPosition);
  72672. };
  72673. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  72674. var _this = this;
  72675. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  72676. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  72677. if (!this.updateCacheCalled) {
  72678. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  72679. this.updateCacheCalled = true;
  72680. this.update();
  72681. }
  72682. // Set working vector to the device position in room space rotated by the new rotation
  72683. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  72684. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  72685. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  72686. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  72687. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  72688. // Add translation from anchor position
  72689. this._deviceToWorld.getTranslationToRef(this._workingVector);
  72690. this._workingVector.addInPlace(this.position);
  72691. this._workingVector.subtractInPlace(this._cache.position);
  72692. this._deviceToWorld.setTranslation(this._workingVector);
  72693. // Set an inverted matrix to be used when updating the camera
  72694. this._deviceToWorld.invertToRef(this._worldToDevice);
  72695. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  72696. this.controllers.forEach(function (controller) {
  72697. controller._deviceToWorld = _this._deviceToWorld;
  72698. controller.update();
  72699. });
  72700. }
  72701. if (!ignoreParentClass) {
  72702. _super.prototype._updateCache.call(this);
  72703. }
  72704. this.updateCacheCalled = false;
  72705. };
  72706. WebVRFreeCamera.prototype.update = function () {
  72707. // Get current device position in babylon world
  72708. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  72709. // Get current device rotation in babylon world
  72710. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  72711. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  72712. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72713. _super.prototype.update.call(this);
  72714. };
  72715. WebVRFreeCamera.prototype._getViewMatrix = function () {
  72716. return BABYLON.Matrix.Identity();
  72717. };
  72718. /**
  72719. * This function is called by the two RIG cameras.
  72720. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  72721. */
  72722. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  72723. var _this = this;
  72724. //WebVR 1.1
  72725. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  72726. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  72727. if (!this.getScene().useRightHandedSystem) {
  72728. [2, 6, 8, 9, 14].forEach(function (num) {
  72729. _this._webvrViewMatrix.m[num] *= -1;
  72730. });
  72731. }
  72732. // update the camera rotation matrix
  72733. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  72734. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  72735. // Computing target and final matrix
  72736. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  72737. var parentCamera = this._cameraRigParams["parentCamera"];
  72738. // should the view matrix be updated with scale and position offset?
  72739. if (parentCamera.deviceScaleFactor !== 1) {
  72740. this._webvrViewMatrix.invert();
  72741. // scale the position, if set
  72742. if (parentCamera.deviceScaleFactor) {
  72743. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  72744. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  72745. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  72746. }
  72747. this._webvrViewMatrix.invert();
  72748. }
  72749. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  72750. return this._webvrViewMatrix;
  72751. };
  72752. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  72753. var _this = this;
  72754. var parentCamera = this.parent;
  72755. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  72756. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  72757. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  72758. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  72759. //babylon compatible matrix
  72760. if (!this.getScene().useRightHandedSystem) {
  72761. [8, 9, 10, 11].forEach(function (num) {
  72762. _this._projectionMatrix.m[num] *= -1;
  72763. });
  72764. }
  72765. return this._projectionMatrix;
  72766. };
  72767. WebVRFreeCamera.prototype.initControllers = function () {
  72768. var _this = this;
  72769. this.controllers = [];
  72770. var manager = this.getScene().gamepadManager;
  72771. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72772. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  72773. var webVrController = gamepad;
  72774. if (webVrController.defaultModel) {
  72775. webVrController.defaultModel.setEnabled(false);
  72776. }
  72777. if (webVrController.hand === "right") {
  72778. _this._rightController = null;
  72779. }
  72780. if (webVrController.hand === "left") {
  72781. _this._rightController = null;
  72782. }
  72783. var controllerIndex = _this.controllers.indexOf(webVrController);
  72784. if (controllerIndex !== -1) {
  72785. _this.controllers.splice(controllerIndex, 1);
  72786. }
  72787. }
  72788. });
  72789. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72790. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  72791. var webVrController_1 = gamepad;
  72792. webVrController_1._deviceToWorld = _this._deviceToWorld;
  72793. if (_this.webVROptions.controllerMeshes) {
  72794. if (webVrController_1.defaultModel) {
  72795. webVrController_1.defaultModel.setEnabled(true);
  72796. }
  72797. else {
  72798. // Load the meshes
  72799. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  72800. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  72801. if (_this.webVROptions.defaultLightingOnControllers) {
  72802. if (!_this._lightOnControllers) {
  72803. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  72804. }
  72805. var activateLightOnSubMeshes_1 = function (mesh, light) {
  72806. var children = mesh.getChildren();
  72807. if (children.length !== 0) {
  72808. children.forEach(function (mesh) {
  72809. light.includedOnlyMeshes.push(mesh);
  72810. activateLightOnSubMeshes_1(mesh, light);
  72811. });
  72812. }
  72813. };
  72814. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  72815. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  72816. }
  72817. });
  72818. }
  72819. }
  72820. webVrController_1.attachToPoseControlledCamera(_this);
  72821. // since this is async - sanity check. Is the controller already stored?
  72822. if (_this.controllers.indexOf(webVrController_1) === -1) {
  72823. //add to the controllers array
  72824. _this.controllers.push(webVrController_1);
  72825. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  72826. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  72827. // So we're overriding setting left & right manually to be sure
  72828. var firstViveWandDetected = false;
  72829. for (var i = 0; i < _this.controllers.length; i++) {
  72830. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  72831. if (!firstViveWandDetected) {
  72832. firstViveWandDetected = true;
  72833. _this.controllers[i].hand = "left";
  72834. }
  72835. else {
  72836. _this.controllers[i].hand = "right";
  72837. }
  72838. }
  72839. }
  72840. //did we find enough controllers? Great! let the developer know.
  72841. if (_this.controllers.length >= 2) {
  72842. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  72843. }
  72844. }
  72845. }
  72846. });
  72847. };
  72848. return WebVRFreeCamera;
  72849. }(BABYLON.FreeCamera));
  72850. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  72851. })(BABYLON || (BABYLON = {}));
  72852. //# sourceMappingURL=babylon.webVRCamera.js.map
  72853. var BABYLON;
  72854. (function (BABYLON) {
  72855. // We're mainly based on the logic defined into the FreeCamera code
  72856. var DeviceOrientationCamera = /** @class */ (function (_super) {
  72857. __extends(DeviceOrientationCamera, _super);
  72858. function DeviceOrientationCamera(name, position, scene) {
  72859. var _this = _super.call(this, name, position, scene) || this;
  72860. _this._quaternionCache = new BABYLON.Quaternion();
  72861. _this.inputs.addDeviceOrientation();
  72862. return _this;
  72863. }
  72864. DeviceOrientationCamera.prototype.getClassName = function () {
  72865. return "DeviceOrientationCamera";
  72866. };
  72867. DeviceOrientationCamera.prototype._checkInputs = function () {
  72868. _super.prototype._checkInputs.call(this);
  72869. this._quaternionCache.copyFrom(this.rotationQuaternion);
  72870. if (this._initialQuaternion) {
  72871. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  72872. }
  72873. };
  72874. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  72875. var _this = this;
  72876. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  72877. //can only work if this camera has a rotation quaternion already.
  72878. if (!this.rotationQuaternion)
  72879. return;
  72880. if (!this._initialQuaternion) {
  72881. this._initialQuaternion = new BABYLON.Quaternion();
  72882. }
  72883. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  72884. ['x', 'y', 'z'].forEach(function (axisName) {
  72885. if (!axis[axisName]) {
  72886. _this._initialQuaternion[axisName] = 0;
  72887. }
  72888. else {
  72889. _this._initialQuaternion[axisName] *= -1;
  72890. }
  72891. });
  72892. this._initialQuaternion.normalize();
  72893. //force rotation update
  72894. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  72895. };
  72896. return DeviceOrientationCamera;
  72897. }(BABYLON.FreeCamera));
  72898. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  72899. })(BABYLON || (BABYLON = {}));
  72900. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  72901. var BABYLON;
  72902. (function (BABYLON) {
  72903. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  72904. __extends(VRDeviceOrientationFreeCamera, _super);
  72905. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  72906. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72907. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72908. var _this = _super.call(this, name, position, scene) || this;
  72909. vrCameraMetrics.compensateDistortion = compensateDistortion;
  72910. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  72911. return _this;
  72912. }
  72913. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  72914. return "VRDeviceOrientationFreeCamera";
  72915. };
  72916. return VRDeviceOrientationFreeCamera;
  72917. }(BABYLON.DeviceOrientationCamera));
  72918. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  72919. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  72920. __extends(VRDeviceOrientationGamepadCamera, _super);
  72921. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  72922. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72923. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72924. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  72925. _this.inputs.addGamepad();
  72926. return _this;
  72927. }
  72928. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  72929. return "VRDeviceOrientationGamepadCamera";
  72930. };
  72931. return VRDeviceOrientationGamepadCamera;
  72932. }(VRDeviceOrientationFreeCamera));
  72933. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  72934. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  72935. __extends(VRDeviceOrientationArcRotateCamera, _super);
  72936. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  72937. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72938. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72939. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72940. vrCameraMetrics.compensateDistortion = compensateDistortion;
  72941. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  72942. _this.inputs.addVRDeviceOrientation();
  72943. return _this;
  72944. }
  72945. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  72946. return "VRDeviceOrientationArcRotateCamera";
  72947. };
  72948. return VRDeviceOrientationArcRotateCamera;
  72949. }(BABYLON.ArcRotateCamera));
  72950. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  72951. })(BABYLON || (BABYLON = {}));
  72952. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  72953. var BABYLON;
  72954. (function (BABYLON) {
  72955. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  72956. __extends(AnaglyphFreeCamera, _super);
  72957. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  72958. var _this = _super.call(this, name, position, scene) || this;
  72959. _this.interaxialDistance = interaxialDistance;
  72960. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72961. return _this;
  72962. }
  72963. AnaglyphFreeCamera.prototype.getClassName = function () {
  72964. return "AnaglyphFreeCamera";
  72965. };
  72966. return AnaglyphFreeCamera;
  72967. }(BABYLON.FreeCamera));
  72968. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  72969. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  72970. __extends(AnaglyphArcRotateCamera, _super);
  72971. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  72972. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72973. _this.interaxialDistance = interaxialDistance;
  72974. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72975. return _this;
  72976. }
  72977. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  72978. return "AnaglyphArcRotateCamera";
  72979. };
  72980. return AnaglyphArcRotateCamera;
  72981. }(BABYLON.ArcRotateCamera));
  72982. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  72983. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  72984. __extends(AnaglyphGamepadCamera, _super);
  72985. function AnaglyphGamepadCamera(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. AnaglyphGamepadCamera.prototype.getClassName = function () {
  72992. return "AnaglyphGamepadCamera";
  72993. };
  72994. return AnaglyphGamepadCamera;
  72995. }(BABYLON.GamepadCamera));
  72996. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  72997. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  72998. __extends(AnaglyphUniversalCamera, _super);
  72999. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  73000. var _this = _super.call(this, name, position, scene) || this;
  73001. _this.interaxialDistance = interaxialDistance;
  73002. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73003. return _this;
  73004. }
  73005. AnaglyphUniversalCamera.prototype.getClassName = function () {
  73006. return "AnaglyphUniversalCamera";
  73007. };
  73008. return AnaglyphUniversalCamera;
  73009. }(BABYLON.UniversalCamera));
  73010. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  73011. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  73012. __extends(StereoscopicFreeCamera, _super);
  73013. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73014. var _this = _super.call(this, name, position, scene) || this;
  73015. _this.interaxialDistance = interaxialDistance;
  73016. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73017. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73018. return _this;
  73019. }
  73020. StereoscopicFreeCamera.prototype.getClassName = function () {
  73021. return "StereoscopicFreeCamera";
  73022. };
  73023. return StereoscopicFreeCamera;
  73024. }(BABYLON.FreeCamera));
  73025. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  73026. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  73027. __extends(StereoscopicArcRotateCamera, _super);
  73028. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  73029. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  73030. _this.interaxialDistance = interaxialDistance;
  73031. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73032. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73033. return _this;
  73034. }
  73035. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  73036. return "StereoscopicArcRotateCamera";
  73037. };
  73038. return StereoscopicArcRotateCamera;
  73039. }(BABYLON.ArcRotateCamera));
  73040. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  73041. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  73042. __extends(StereoscopicGamepadCamera, _super);
  73043. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73044. var _this = _super.call(this, name, position, scene) || this;
  73045. _this.interaxialDistance = interaxialDistance;
  73046. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73047. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73048. return _this;
  73049. }
  73050. StereoscopicGamepadCamera.prototype.getClassName = function () {
  73051. return "StereoscopicGamepadCamera";
  73052. };
  73053. return StereoscopicGamepadCamera;
  73054. }(BABYLON.GamepadCamera));
  73055. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  73056. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  73057. __extends(StereoscopicUniversalCamera, _super);
  73058. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73059. var _this = _super.call(this, name, position, scene) || this;
  73060. _this.interaxialDistance = interaxialDistance;
  73061. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73062. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73063. return _this;
  73064. }
  73065. StereoscopicUniversalCamera.prototype.getClassName = function () {
  73066. return "StereoscopicUniversalCamera";
  73067. };
  73068. return StereoscopicUniversalCamera;
  73069. }(BABYLON.UniversalCamera));
  73070. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  73071. })(BABYLON || (BABYLON = {}));
  73072. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  73073. var BABYLON;
  73074. (function (BABYLON) {
  73075. var VRExperienceHelper = /** @class */ (function () {
  73076. function VRExperienceHelper(scene, webVROptions) {
  73077. if (webVROptions === void 0) { webVROptions = {}; }
  73078. var _this = this;
  73079. this.webVROptions = webVROptions;
  73080. // Can the system support WebVR, even if a headset isn't plugged in?
  73081. this._webVRsupported = false;
  73082. // If WebVR is supported, is a headset plugged in and are we ready to present?
  73083. this._webVRready = false;
  73084. // Are we waiting for the requestPresent callback to complete?
  73085. this._webVRrequesting = false;
  73086. // Are we presenting to the headset right now?
  73087. this._webVRpresenting = false;
  73088. // Are we presenting in the fullscreen fallback?
  73089. this._fullscreenVRpresenting = false;
  73090. /**
  73091. * Observable raised when entering VR.
  73092. */
  73093. this.onEnteringVRObservable = new BABYLON.Observable();
  73094. /**
  73095. * Observable raised when exiting VR.
  73096. */
  73097. this.onExitingVRObservable = new BABYLON.Observable();
  73098. /**
  73099. * Observable raised when controller mesh is loaded.
  73100. */
  73101. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  73102. this._useCustomVRButton = false;
  73103. this._teleportationRequested = false;
  73104. this._teleportationEnabledOnLeftController = false;
  73105. this._teleportationEnabledOnRightController = false;
  73106. this._interactionsEnabledOnLeftController = false;
  73107. this._interactionsEnabledOnRightController = false;
  73108. this._leftControllerReady = false;
  73109. this._rightControllerReady = false;
  73110. this._floorMeshesCollection = [];
  73111. this._teleportationAllowed = false;
  73112. this._rotationAllowed = true;
  73113. this._teleportationRequestInitiated = false;
  73114. this._teleportationBackRequestInitiated = false;
  73115. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  73116. this._rotationRightAsked = false;
  73117. this._rotationLeftAsked = false;
  73118. this._isDefaultTeleportationTarget = true;
  73119. this._teleportationFillColor = "#444444";
  73120. this._teleportationBorderColor = "#FFFFFF";
  73121. this._rotationAngle = 0;
  73122. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  73123. this._padSensibilityUp = 0.65;
  73124. this._padSensibilityDown = 0.35;
  73125. /**
  73126. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  73127. */
  73128. this.onNewMeshSelected = new BABYLON.Observable();
  73129. /**
  73130. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  73131. */
  73132. this.onNewMeshPicked = new BABYLON.Observable();
  73133. /**
  73134. * Observable raised before camera teleportation
  73135. */
  73136. this.onBeforeCameraTeleport = new BABYLON.Observable();
  73137. /**
  73138. * Observable raised after camera teleportation
  73139. */
  73140. this.onAfterCameraTeleport = new BABYLON.Observable();
  73141. /**
  73142. * Observable raised when current selected mesh gets unselected
  73143. */
  73144. this.onSelectedMeshUnselected = new BABYLON.Observable();
  73145. /**
  73146. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  73147. */
  73148. this.teleportationEnabled = true;
  73149. this._pointerDownOnMeshAsked = false;
  73150. this._isActionableMesh = false;
  73151. this._teleportationInitialized = false;
  73152. this._interactionsEnabled = false;
  73153. this._interactionsRequested = false;
  73154. this._displayGaze = true;
  73155. this._displayLaserPointer = true;
  73156. this._dpadPressed = true;
  73157. this._onResize = function () {
  73158. _this.moveButtonToBottomRight();
  73159. if (_this._fullscreenVRpresenting && _this._webVRready) {
  73160. _this.exitVR();
  73161. }
  73162. };
  73163. this._onFullscreenChange = function () {
  73164. if (document.fullscreen !== undefined) {
  73165. _this._fullscreenVRpresenting = document.fullscreen;
  73166. }
  73167. else if (document.mozFullScreen !== undefined) {
  73168. _this._fullscreenVRpresenting = document.mozFullScreen;
  73169. }
  73170. else if (document.webkitIsFullScreen !== undefined) {
  73171. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  73172. }
  73173. else if (document.msIsFullScreen !== undefined) {
  73174. _this._fullscreenVRpresenting = document.msIsFullScreen;
  73175. }
  73176. if (!_this._fullscreenVRpresenting && _this._canvas) {
  73177. _this.exitVR();
  73178. if (!_this._useCustomVRButton) {
  73179. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  73180. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  73181. }
  73182. }
  73183. };
  73184. this.beforeRender = function () {
  73185. _this._castRayAndSelectObject();
  73186. };
  73187. this._onNewGamepadConnected = function (gamepad) {
  73188. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73189. if (gamepad.leftStick) {
  73190. gamepad.onleftstickchanged(function (stickValues) {
  73191. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  73192. // Listening to classic/xbox gamepad only if no VR controller is active
  73193. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  73194. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  73195. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  73196. _this._checkTeleportWithRay(stickValues);
  73197. _this._checkTeleportBackwards(stickValues);
  73198. }
  73199. }
  73200. });
  73201. }
  73202. if (gamepad.rightStick) {
  73203. gamepad.onrightstickchanged(function (stickValues) {
  73204. if (_this._teleportationInitialized) {
  73205. _this._checkRotate(stickValues);
  73206. }
  73207. });
  73208. }
  73209. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  73210. gamepad.onbuttondown(function (buttonPressed) {
  73211. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  73212. _this._selectionPointerDown();
  73213. }
  73214. });
  73215. gamepad.onbuttonup(function (buttonPressed) {
  73216. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  73217. _this._selectionPointerUp();
  73218. }
  73219. });
  73220. }
  73221. }
  73222. else {
  73223. var webVRController = gamepad;
  73224. _this._tryEnableInteractionOnController(webVRController);
  73225. }
  73226. };
  73227. // 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
  73228. this._tryEnableInteractionOnController = function (webVRController) {
  73229. if (webVRController.hand === "left") {
  73230. _this._leftControllerReady = true;
  73231. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  73232. _this._enableInteractionOnController(webVRController);
  73233. }
  73234. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  73235. _this._enableTeleportationOnController(webVRController);
  73236. }
  73237. }
  73238. if (webVRController.hand === "right") {
  73239. _this._rightControllerReady = true;
  73240. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  73241. _this._enableInteractionOnController(webVRController);
  73242. }
  73243. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  73244. _this._enableTeleportationOnController(webVRController);
  73245. }
  73246. }
  73247. };
  73248. this._onNewGamepadDisconnected = function (gamepad) {
  73249. if (gamepad instanceof BABYLON.WebVRController) {
  73250. if (gamepad.hand === "left") {
  73251. _this._interactionsEnabledOnLeftController = false;
  73252. _this._teleportationEnabledOnLeftController = false;
  73253. _this._leftControllerReady = false;
  73254. if (_this._leftLaserPointer) {
  73255. _this._leftLaserPointer.dispose();
  73256. }
  73257. }
  73258. if (gamepad.hand === "right") {
  73259. _this._interactionsEnabledOnRightController = false;
  73260. _this._teleportationEnabledOnRightController = false;
  73261. _this._rightControllerReady = false;
  73262. if (_this._rightLaserPointer) {
  73263. _this._rightLaserPointer.dispose();
  73264. }
  73265. }
  73266. }
  73267. };
  73268. this._workingVector = BABYLON.Vector3.Zero();
  73269. this._workingQuaternion = BABYLON.Quaternion.Identity();
  73270. this._workingMatrix = BABYLON.Matrix.Identity();
  73271. this._scene = scene;
  73272. this._canvas = scene.getEngine().getRenderingCanvas();
  73273. // Parse options
  73274. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  73275. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  73276. }
  73277. if (webVROptions.createDeviceOrientationCamera === undefined) {
  73278. webVROptions.createDeviceOrientationCamera = true;
  73279. }
  73280. if (webVROptions.defaultHeight === undefined) {
  73281. webVROptions.defaultHeight = 1.7;
  73282. }
  73283. if (webVROptions.useCustomVRButton) {
  73284. this._useCustomVRButton = true;
  73285. if (webVROptions.customVRButton) {
  73286. this._btnVR = webVROptions.customVRButton;
  73287. }
  73288. }
  73289. if (webVROptions.rayLength) {
  73290. this._rayLength = webVROptions.rayLength;
  73291. }
  73292. this._defaultHeight = webVROptions.defaultHeight;
  73293. // Set position
  73294. if (this._scene.activeCamera) {
  73295. this._position = this._scene.activeCamera.position.clone();
  73296. }
  73297. else {
  73298. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  73299. }
  73300. // Set non-vr camera
  73301. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  73302. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  73303. // Copy data from existing camera
  73304. if (this._scene.activeCamera) {
  73305. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  73306. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  73307. // Set rotation from previous camera
  73308. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  73309. var targetCamera = this._scene.activeCamera;
  73310. if (targetCamera.rotationQuaternion) {
  73311. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  73312. }
  73313. else {
  73314. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  73315. }
  73316. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  73317. }
  73318. }
  73319. this._scene.activeCamera = this._deviceOrientationCamera;
  73320. if (this._canvas) {
  73321. this._scene.activeCamera.attachControl(this._canvas);
  73322. }
  73323. }
  73324. else {
  73325. this._existingCamera = this._scene.activeCamera;
  73326. }
  73327. // Create VR cameras
  73328. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  73329. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  73330. }
  73331. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  73332. this._webVRCamera.useStandingMatrix();
  73333. // Create default button
  73334. if (!this._useCustomVRButton) {
  73335. this._btnVR = document.createElement("BUTTON");
  73336. this._btnVR.className = "babylonVRicon";
  73337. this._btnVR.id = "babylonVRiconbtn";
  73338. this._btnVR.title = "Click to switch to VR";
  73339. 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) }";
  73340. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  73341. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  73342. // css += ".babylonVRicon.vrdisplaysupported { }";
  73343. // css += ".babylonVRicon.vrdisplayready { }";
  73344. // css += ".babylonVRicon.vrdisplayrequesting { }";
  73345. var style = document.createElement('style');
  73346. style.appendChild(document.createTextNode(css));
  73347. document.getElementsByTagName('head')[0].appendChild(style);
  73348. this.moveButtonToBottomRight();
  73349. }
  73350. // VR button click event
  73351. if (this._btnVR) {
  73352. this._btnVR.addEventListener("click", function () {
  73353. if (!_this.isInVRMode) {
  73354. _this.enterVR();
  73355. }
  73356. else {
  73357. _this.exitVR();
  73358. }
  73359. });
  73360. }
  73361. // Window events
  73362. window.addEventListener("resize", this._onResize);
  73363. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  73364. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  73365. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  73366. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  73367. // Display vr button when headset is connected
  73368. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  73369. this.displayVRButton();
  73370. }
  73371. else {
  73372. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  73373. if (e.vrDisplay) {
  73374. _this.displayVRButton();
  73375. }
  73376. });
  73377. }
  73378. // Exiting VR mode using 'ESC' key on desktop
  73379. this._onKeyDown = function (event) {
  73380. if (event.keyCode === 27 && _this.isInVRMode) {
  73381. _this.exitVR();
  73382. }
  73383. };
  73384. document.addEventListener("keydown", this._onKeyDown);
  73385. // Exiting VR mode double tapping the touch screen
  73386. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  73387. if (_this.isInVRMode) {
  73388. _this.exitVR();
  73389. if (_this._fullscreenVRpresenting) {
  73390. _this._scene.getEngine().switchFullscreen(true);
  73391. }
  73392. }
  73393. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  73394. // Listen for WebVR display changes
  73395. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  73396. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  73397. this._onVRRequestPresentStart = function () {
  73398. _this._webVRrequesting = true;
  73399. _this.updateButtonVisibility();
  73400. };
  73401. this._onVRRequestPresentComplete = function (success) {
  73402. _this._webVRrequesting = false;
  73403. _this.updateButtonVisibility();
  73404. };
  73405. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  73406. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  73407. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  73408. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  73409. scene.onDisposeObservable.add(function () {
  73410. _this.dispose();
  73411. });
  73412. // Gamepad connection events
  73413. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  73414. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  73415. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  73416. this.updateButtonVisibility();
  73417. //create easing functions
  73418. this._circleEase = new BABYLON.CircleEase();
  73419. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  73420. }
  73421. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  73422. /** Return this.onEnteringVRObservable
  73423. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  73424. */
  73425. get: function () {
  73426. return this.onEnteringVRObservable;
  73427. },
  73428. enumerable: true,
  73429. configurable: true
  73430. });
  73431. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  73432. /** Return this.onExitingVRObservable
  73433. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  73434. */
  73435. get: function () {
  73436. return this.onExitingVRObservable;
  73437. },
  73438. enumerable: true,
  73439. configurable: true
  73440. });
  73441. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  73442. /** Return this.onControllerMeshLoadedObservable
  73443. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  73444. */
  73445. get: function () {
  73446. return this.onControllerMeshLoadedObservable;
  73447. },
  73448. enumerable: true,
  73449. configurable: true
  73450. });
  73451. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  73452. get: function () {
  73453. return this._teleportationTarget;
  73454. },
  73455. set: function (value) {
  73456. if (value) {
  73457. value.name = "teleportationTarget";
  73458. this._isDefaultTeleportationTarget = false;
  73459. this._teleportationTarget = value;
  73460. }
  73461. },
  73462. enumerable: true,
  73463. configurable: true
  73464. });
  73465. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  73466. get: function () {
  73467. return this._displayGaze;
  73468. },
  73469. set: function (value) {
  73470. this._displayGaze = value;
  73471. if (!value) {
  73472. this._gazeTracker.isVisible = false;
  73473. }
  73474. },
  73475. enumerable: true,
  73476. configurable: true
  73477. });
  73478. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  73479. get: function () {
  73480. return this._displayLaserPointer;
  73481. },
  73482. set: function (value) {
  73483. this._displayLaserPointer = value;
  73484. if (!value) {
  73485. if (this._rightLaserPointer) {
  73486. this._rightLaserPointer.isVisible = false;
  73487. }
  73488. if (this._leftLaserPointer) {
  73489. this._leftLaserPointer.isVisible = false;
  73490. }
  73491. }
  73492. else {
  73493. if (this._rightLaserPointer) {
  73494. this._rightLaserPointer.isVisible = true;
  73495. }
  73496. else if (this._leftLaserPointer) {
  73497. this._leftLaserPointer.isVisible = true;
  73498. }
  73499. }
  73500. },
  73501. enumerable: true,
  73502. configurable: true
  73503. });
  73504. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  73505. get: function () {
  73506. return this._deviceOrientationCamera;
  73507. },
  73508. enumerable: true,
  73509. configurable: true
  73510. });
  73511. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  73512. // Based on the current WebVR support, returns the current VR camera used
  73513. get: function () {
  73514. if (this._webVRready) {
  73515. return this._webVRCamera;
  73516. }
  73517. else {
  73518. return this._scene.activeCamera;
  73519. }
  73520. },
  73521. enumerable: true,
  73522. configurable: true
  73523. });
  73524. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  73525. get: function () {
  73526. return this._webVRCamera;
  73527. },
  73528. enumerable: true,
  73529. configurable: true
  73530. });
  73531. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  73532. get: function () {
  73533. return this._vrDeviceOrientationCamera;
  73534. },
  73535. enumerable: true,
  73536. configurable: true
  73537. });
  73538. // Raised when one of the controller has loaded successfully its associated default mesh
  73539. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  73540. this._tryEnableInteractionOnController(webVRController);
  73541. try {
  73542. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  73543. }
  73544. catch (err) {
  73545. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  73546. }
  73547. };
  73548. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  73549. /**
  73550. * Gets a value indicating if we are currently in VR mode.
  73551. */
  73552. get: function () {
  73553. return this._webVRpresenting || this._fullscreenVRpresenting;
  73554. },
  73555. enumerable: true,
  73556. configurable: true
  73557. });
  73558. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  73559. var vrDisplay = this._scene.getEngine().getVRDevice();
  73560. if (vrDisplay) {
  73561. var wasPresenting = this._webVRpresenting;
  73562. // A VR display is connected
  73563. this._webVRpresenting = vrDisplay.isPresenting;
  73564. if (wasPresenting && !this._webVRpresenting)
  73565. this.exitVR();
  73566. }
  73567. else {
  73568. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  73569. }
  73570. this.updateButtonVisibility();
  73571. };
  73572. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  73573. this._webVRsupported = eventArgs.vrSupported;
  73574. this._webVRready = !!eventArgs.vrDisplay;
  73575. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  73576. this.updateButtonVisibility();
  73577. };
  73578. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  73579. if (this._canvas && !this._useCustomVRButton) {
  73580. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  73581. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  73582. }
  73583. };
  73584. VRExperienceHelper.prototype.displayVRButton = function () {
  73585. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  73586. document.body.appendChild(this._btnVR);
  73587. this._btnVRDisplayed = true;
  73588. }
  73589. };
  73590. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  73591. if (!this._btnVR || this._useCustomVRButton) {
  73592. return;
  73593. }
  73594. this._btnVR.className = "babylonVRicon";
  73595. if (this.isInVRMode) {
  73596. this._btnVR.className += " vrdisplaypresenting";
  73597. }
  73598. else {
  73599. if (this._webVRready)
  73600. this._btnVR.className += " vrdisplayready";
  73601. if (this._webVRsupported)
  73602. this._btnVR.className += " vrdisplaysupported";
  73603. if (this._webVRrequesting)
  73604. this._btnVR.className += " vrdisplayrequesting";
  73605. }
  73606. };
  73607. /**
  73608. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  73609. * Otherwise, will use the fullscreen API.
  73610. */
  73611. VRExperienceHelper.prototype.enterVR = function () {
  73612. if (this.onEnteringVRObservable) {
  73613. try {
  73614. this.onEnteringVRObservable.notifyObservers(this);
  73615. }
  73616. catch (err) {
  73617. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  73618. }
  73619. }
  73620. if (this._scene.activeCamera) {
  73621. this._position = this._scene.activeCamera.position.clone();
  73622. // make sure that we return to the last active camera
  73623. this._existingCamera = this._scene.activeCamera;
  73624. }
  73625. if (this._webVRrequesting)
  73626. return;
  73627. // If WebVR is supported and a headset is connected
  73628. if (this._webVRready) {
  73629. if (!this._webVRpresenting) {
  73630. this._webVRCamera.position = this._position;
  73631. this._scene.activeCamera = this._webVRCamera;
  73632. }
  73633. }
  73634. else if (this._vrDeviceOrientationCamera) {
  73635. this._vrDeviceOrientationCamera.position = this._position;
  73636. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  73637. this._scene.getEngine().switchFullscreen(true);
  73638. this.updateButtonVisibility();
  73639. }
  73640. if (this._scene.activeCamera && this._canvas) {
  73641. this._scene.activeCamera.attachControl(this._canvas);
  73642. }
  73643. if (this._interactionsEnabled) {
  73644. this._scene.registerBeforeRender(this.beforeRender);
  73645. }
  73646. };
  73647. /**
  73648. * Attempt to exit VR, or fullscreen.
  73649. */
  73650. VRExperienceHelper.prototype.exitVR = function () {
  73651. if (this.onExitingVRObservable) {
  73652. try {
  73653. this.onExitingVRObservable.notifyObservers(this);
  73654. }
  73655. catch (err) {
  73656. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  73657. }
  73658. }
  73659. if (this._webVRpresenting) {
  73660. this._scene.getEngine().disableVR();
  73661. }
  73662. if (this._scene.activeCamera) {
  73663. this._position = this._scene.activeCamera.position.clone();
  73664. }
  73665. if (this._deviceOrientationCamera) {
  73666. this._deviceOrientationCamera.position = this._position;
  73667. this._scene.activeCamera = this._deviceOrientationCamera;
  73668. if (this._canvas) {
  73669. this._scene.activeCamera.attachControl(this._canvas);
  73670. }
  73671. }
  73672. else if (this._existingCamera) {
  73673. this._existingCamera.position = this._position;
  73674. this._scene.activeCamera = this._existingCamera;
  73675. }
  73676. this.updateButtonVisibility();
  73677. if (this._interactionsEnabled) {
  73678. this._scene.unregisterBeforeRender(this.beforeRender);
  73679. }
  73680. };
  73681. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  73682. get: function () {
  73683. return this._position;
  73684. },
  73685. set: function (value) {
  73686. this._position = value;
  73687. if (this._scene.activeCamera) {
  73688. this._scene.activeCamera.position = value;
  73689. }
  73690. },
  73691. enumerable: true,
  73692. configurable: true
  73693. });
  73694. VRExperienceHelper.prototype.enableInteractions = function () {
  73695. var _this = this;
  73696. if (!this._interactionsEnabled) {
  73697. this._interactionsRequested = true;
  73698. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73699. this._enableInteractionOnController(this._webVRCamera.leftController);
  73700. }
  73701. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73702. this._enableInteractionOnController(this._webVRCamera.rightController);
  73703. }
  73704. this._createGazeTracker();
  73705. this.raySelectionPredicate = function (mesh) {
  73706. return mesh.isVisible;
  73707. };
  73708. this.meshSelectionPredicate = function (mesh) {
  73709. return true;
  73710. };
  73711. this._raySelectionPredicate = function (mesh) {
  73712. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  73713. && mesh.name.indexOf("teleportationTarget") === -1
  73714. && mesh.name.indexOf("torusTeleportation") === -1
  73715. && mesh.name.indexOf("laserPointer") === -1)) {
  73716. return _this.raySelectionPredicate(mesh);
  73717. }
  73718. return false;
  73719. };
  73720. this._interactionsEnabled = true;
  73721. }
  73722. };
  73723. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  73724. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  73725. if (this._floorMeshesCollection[i].id === mesh.id) {
  73726. return true;
  73727. }
  73728. }
  73729. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  73730. return true;
  73731. }
  73732. return false;
  73733. };
  73734. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  73735. if (!this._floorMeshesCollection) {
  73736. return;
  73737. }
  73738. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  73739. return;
  73740. }
  73741. this._floorMeshesCollection.push(floorMesh);
  73742. };
  73743. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  73744. if (!this._floorMeshesCollection) {
  73745. return;
  73746. }
  73747. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  73748. if (meshIndex !== -1) {
  73749. this._floorMeshesCollection.splice(meshIndex, 1);
  73750. }
  73751. };
  73752. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  73753. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  73754. if (!this._teleportationInitialized) {
  73755. this._teleportationRequested = true;
  73756. this.enableInteractions();
  73757. if (vrTeleportationOptions.floorMeshName) {
  73758. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  73759. }
  73760. if (vrTeleportationOptions.floorMeshes) {
  73761. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  73762. }
  73763. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73764. this._enableTeleportationOnController(this._webVRCamera.leftController);
  73765. }
  73766. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73767. this._enableTeleportationOnController(this._webVRCamera.rightController);
  73768. }
  73769. // Creates an image processing post process for the vignette not relying
  73770. // on the main scene configuration for image processing to reduce setup and spaces
  73771. // (gamma/linear) conflicts.
  73772. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  73773. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  73774. imageProcessingConfiguration.vignetteEnabled = true;
  73775. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  73776. this._webVRCamera.detachPostProcess(this._postProcessMove);
  73777. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  73778. this._teleportationInitialized = true;
  73779. if (this._isDefaultTeleportationTarget) {
  73780. this._createTeleportationCircles();
  73781. }
  73782. }
  73783. };
  73784. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  73785. var _this = this;
  73786. var controllerMesh = webVRController.mesh;
  73787. if (controllerMesh) {
  73788. var makeNotPick = function (root) {
  73789. root.name += " laserPointer";
  73790. root.getChildMeshes().forEach(function (c) {
  73791. makeNotPick(c);
  73792. });
  73793. };
  73794. makeNotPick(controllerMesh);
  73795. var childMeshes = controllerMesh.getChildMeshes();
  73796. for (var i = 0; i < childMeshes.length; i++) {
  73797. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  73798. controllerMesh = childMeshes[i];
  73799. break;
  73800. }
  73801. }
  73802. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  73803. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  73804. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  73805. laserPointerMaterial.alpha = 0.6;
  73806. laserPointer.material = laserPointerMaterial;
  73807. laserPointer.rotation.x = Math.PI / 2;
  73808. laserPointer.parent = controllerMesh;
  73809. laserPointer.position.z = -0.5;
  73810. laserPointer.isVisible = false;
  73811. if (webVRController.hand === "left") {
  73812. this._leftLaserPointer = laserPointer;
  73813. this._interactionsEnabledOnLeftController = true;
  73814. if (!this._rightLaserPointer) {
  73815. this._leftLaserPointer.isVisible = true;
  73816. }
  73817. }
  73818. else {
  73819. this._rightLaserPointer = laserPointer;
  73820. this._interactionsEnabledOnRightController = true;
  73821. if (!this._leftLaserPointer) {
  73822. this._rightLaserPointer.isVisible = true;
  73823. }
  73824. }
  73825. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  73826. // Enabling / disabling laserPointer
  73827. if (_this._displayLaserPointer && stateObject.value === 1) {
  73828. laserPointer.isVisible = !laserPointer.isVisible;
  73829. // Laser pointer can only be active on left or right, not both at the same time
  73830. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  73831. _this._rightLaserPointer.isVisible = false;
  73832. }
  73833. else if (_this._leftLaserPointer) {
  73834. _this._leftLaserPointer.isVisible = false;
  73835. }
  73836. }
  73837. });
  73838. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  73839. if (!_this._pointerDownOnMeshAsked) {
  73840. if (stateObject.value > _this._padSensibilityUp) {
  73841. _this._selectionPointerDown();
  73842. }
  73843. }
  73844. else if (stateObject.value < _this._padSensibilityDown) {
  73845. _this._selectionPointerUp();
  73846. }
  73847. });
  73848. }
  73849. };
  73850. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  73851. if (webVRController === void 0) { webVRController = null; }
  73852. if (!this._teleportationRequestInitiated) {
  73853. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  73854. if (webVRController) {
  73855. // If laser pointer wasn't enabled yet
  73856. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  73857. this._leftLaserPointer.isVisible = true;
  73858. if (this._rightLaserPointer) {
  73859. this._rightLaserPointer.isVisible = false;
  73860. }
  73861. }
  73862. else if (this._displayLaserPointer && this._rightLaserPointer) {
  73863. this._rightLaserPointer.isVisible = true;
  73864. if (this._leftLaserPointer) {
  73865. this._leftLaserPointer.isVisible = false;
  73866. }
  73867. }
  73868. }
  73869. this._teleportationRequestInitiated = true;
  73870. }
  73871. }
  73872. else {
  73873. // Listening to the proper controller values changes to confirm teleportation
  73874. if (webVRController == null
  73875. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  73876. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  73877. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  73878. if (this._teleportationAllowed) {
  73879. this._teleportationAllowed = false;
  73880. this._teleportCamera();
  73881. }
  73882. this._teleportationRequestInitiated = false;
  73883. }
  73884. }
  73885. }
  73886. };
  73887. VRExperienceHelper.prototype._selectionPointerDown = function () {
  73888. this._pointerDownOnMeshAsked = true;
  73889. if (this._currentMeshSelected && this._currentHit) {
  73890. this._scene.simulatePointerDown(this._currentHit);
  73891. }
  73892. };
  73893. VRExperienceHelper.prototype._selectionPointerUp = function () {
  73894. if (this._currentMeshSelected && this._currentHit) {
  73895. this._scene.simulatePointerUp(this._currentHit);
  73896. }
  73897. this._pointerDownOnMeshAsked = false;
  73898. };
  73899. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  73900. // Only rotate when user is not currently selecting a teleportation location
  73901. if (this._teleportationRequestInitiated) {
  73902. return;
  73903. }
  73904. if (!this._rotationLeftAsked) {
  73905. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  73906. this._rotationLeftAsked = true;
  73907. if (this._rotationAllowed) {
  73908. this._rotateCamera(false);
  73909. }
  73910. }
  73911. }
  73912. else {
  73913. if (stateObject.x > -this._padSensibilityDown) {
  73914. this._rotationLeftAsked = false;
  73915. }
  73916. }
  73917. if (!this._rotationRightAsked) {
  73918. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  73919. this._rotationRightAsked = true;
  73920. if (this._rotationAllowed) {
  73921. this._rotateCamera(true);
  73922. }
  73923. }
  73924. }
  73925. else {
  73926. if (stateObject.x < this._padSensibilityDown) {
  73927. this._rotationRightAsked = false;
  73928. }
  73929. }
  73930. };
  73931. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  73932. // Only teleport backwards when user is not currently selecting a teleportation location
  73933. if (this._teleportationRequestInitiated) {
  73934. return;
  73935. }
  73936. // Teleport backwards
  73937. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  73938. if (!this._teleportationBackRequestInitiated) {
  73939. if (!this.currentVRCamera) {
  73940. return;
  73941. }
  73942. // Get rotation and position of the current camera
  73943. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  73944. var position = this.currentVRCamera.position;
  73945. // If the camera has device position, use that instead
  73946. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  73947. rotation = this.currentVRCamera.deviceRotationQuaternion;
  73948. position = this.currentVRCamera.devicePosition;
  73949. }
  73950. // Get matrix with only the y rotation of the device rotation
  73951. rotation.toEulerAnglesToRef(this._workingVector);
  73952. this._workingVector.z = 0;
  73953. this._workingVector.x = 0;
  73954. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  73955. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  73956. // Rotate backwards ray by device rotation to cast at the ground behind the user
  73957. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  73958. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  73959. var ray = new BABYLON.Ray(position, this._workingVector);
  73960. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  73961. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  73962. this._teleportCamera(hit.pickedPoint);
  73963. }
  73964. this._teleportationBackRequestInitiated = true;
  73965. }
  73966. }
  73967. else {
  73968. this._teleportationBackRequestInitiated = false;
  73969. }
  73970. };
  73971. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  73972. var _this = this;
  73973. var controllerMesh = webVRController.mesh;
  73974. if (controllerMesh) {
  73975. if (webVRController.hand === "left") {
  73976. if (!this._interactionsEnabledOnLeftController) {
  73977. this._enableInteractionOnController(webVRController);
  73978. }
  73979. this._teleportationEnabledOnLeftController = true;
  73980. }
  73981. else {
  73982. if (!this._interactionsEnabledOnRightController) {
  73983. this._enableInteractionOnController(webVRController);
  73984. }
  73985. this._teleportationEnabledOnRightController = true;
  73986. }
  73987. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  73988. this._dpadPressed = false;
  73989. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  73990. _this._dpadPressed = stateObject.pressed;
  73991. if (!_this._dpadPressed) {
  73992. _this._rotationLeftAsked = false;
  73993. _this._rotationRightAsked = false;
  73994. _this._teleportationBackRequestInitiated = false;
  73995. }
  73996. });
  73997. }
  73998. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  73999. if (_this.teleportationEnabled) {
  74000. _this._checkTeleportBackwards(stateObject);
  74001. _this._checkTeleportWithRay(stateObject, webVRController);
  74002. }
  74003. _this._checkRotate(stateObject);
  74004. });
  74005. }
  74006. };
  74007. // Gaze support used to point to teleport or to interact with an object
  74008. VRExperienceHelper.prototype._createGazeTracker = function () {
  74009. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  74010. this._gazeTracker.bakeCurrentTransformIntoVertices();
  74011. this._gazeTracker.isPickable = false;
  74012. this._gazeTracker.isVisible = false;
  74013. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  74014. targetMat.specularColor = BABYLON.Color3.Black();
  74015. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  74016. targetMat.backFaceCulling = false;
  74017. this._gazeTracker.material = targetMat;
  74018. };
  74019. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  74020. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  74021. this._teleportationTarget.isPickable = false;
  74022. var length = 512;
  74023. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  74024. dynamicTexture.hasAlpha = true;
  74025. var context = dynamicTexture.getContext();
  74026. var centerX = length / 2;
  74027. var centerY = length / 2;
  74028. var radius = 200;
  74029. context.beginPath();
  74030. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  74031. context.fillStyle = this._teleportationFillColor;
  74032. context.fill();
  74033. context.lineWidth = 10;
  74034. context.strokeStyle = this._teleportationBorderColor;
  74035. context.stroke();
  74036. context.closePath();
  74037. dynamicTexture.update();
  74038. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  74039. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  74040. this._teleportationTarget.material = teleportationCircleMaterial;
  74041. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  74042. torus.isPickable = false;
  74043. torus.parent = this._teleportationTarget;
  74044. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  74045. var keys = [];
  74046. keys.push({
  74047. frame: 0,
  74048. value: 0
  74049. });
  74050. keys.push({
  74051. frame: 30,
  74052. value: 0.4
  74053. });
  74054. keys.push({
  74055. frame: 60,
  74056. value: 0
  74057. });
  74058. animationInnerCircle.setKeys(keys);
  74059. var easingFunction = new BABYLON.SineEase();
  74060. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  74061. animationInnerCircle.setEasingFunction(easingFunction);
  74062. torus.animations = [];
  74063. torus.animations.push(animationInnerCircle);
  74064. this._scene.beginAnimation(torus, 0, 60, true);
  74065. this._hideTeleportationTarget();
  74066. };
  74067. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  74068. if (this._teleportationInitialized) {
  74069. this._teleportationTarget.isVisible = true;
  74070. if (this._isDefaultTeleportationTarget) {
  74071. this._teleportationTarget.getChildren()[0].isVisible = true;
  74072. }
  74073. }
  74074. };
  74075. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  74076. if (this._teleportationInitialized) {
  74077. this._teleportationTarget.isVisible = false;
  74078. if (this._isDefaultTeleportationTarget) {
  74079. this._teleportationTarget.getChildren()[0].isVisible = false;
  74080. }
  74081. }
  74082. };
  74083. VRExperienceHelper.prototype._rotateCamera = function (right) {
  74084. var _this = this;
  74085. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74086. return;
  74087. }
  74088. if (right) {
  74089. this._rotationAngle++;
  74090. }
  74091. else {
  74092. this._rotationAngle--;
  74093. }
  74094. this.currentVRCamera.animations = [];
  74095. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  74096. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74097. var animationRotationKeys = [];
  74098. animationRotationKeys.push({
  74099. frame: 0,
  74100. value: this.currentVRCamera.rotationQuaternion
  74101. });
  74102. animationRotationKeys.push({
  74103. frame: 6,
  74104. value: target
  74105. });
  74106. animationRotation.setKeys(animationRotationKeys);
  74107. animationRotation.setEasingFunction(this._circleEase);
  74108. this.currentVRCamera.animations.push(animationRotation);
  74109. this._postProcessMove.animations = [];
  74110. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74111. var vignetteWeightKeys = [];
  74112. vignetteWeightKeys.push({
  74113. frame: 0,
  74114. value: 0
  74115. });
  74116. vignetteWeightKeys.push({
  74117. frame: 3,
  74118. value: 4
  74119. });
  74120. vignetteWeightKeys.push({
  74121. frame: 6,
  74122. value: 0
  74123. });
  74124. animationPP.setKeys(vignetteWeightKeys);
  74125. animationPP.setEasingFunction(this._circleEase);
  74126. this._postProcessMove.animations.push(animationPP);
  74127. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74128. var vignetteStretchKeys = [];
  74129. vignetteStretchKeys.push({
  74130. frame: 0,
  74131. value: 0
  74132. });
  74133. vignetteStretchKeys.push({
  74134. frame: 3,
  74135. value: 10
  74136. });
  74137. vignetteStretchKeys.push({
  74138. frame: 6,
  74139. value: 0
  74140. });
  74141. animationPP2.setKeys(vignetteStretchKeys);
  74142. animationPP2.setEasingFunction(this._circleEase);
  74143. this._postProcessMove.animations.push(animationPP2);
  74144. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  74145. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  74146. this._webVRCamera.attachPostProcess(this._postProcessMove);
  74147. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  74148. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  74149. });
  74150. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  74151. };
  74152. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  74153. if (hit.pickedPoint) {
  74154. this._teleportationAllowed = true;
  74155. if (this._teleportationRequestInitiated) {
  74156. this._displayTeleportationTarget();
  74157. }
  74158. else {
  74159. this._hideTeleportationTarget();
  74160. }
  74161. this._haloCenter.copyFrom(hit.pickedPoint);
  74162. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  74163. var pickNormal = hit.getNormal(true, false);
  74164. if (pickNormal) {
  74165. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  74166. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  74167. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  74168. }
  74169. this._teleportationTarget.position.y += 0.1;
  74170. }
  74171. };
  74172. VRExperienceHelper.prototype._teleportCamera = function (location) {
  74173. var _this = this;
  74174. if (location === void 0) { location = null; }
  74175. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74176. return;
  74177. }
  74178. if (!location) {
  74179. location = this._haloCenter;
  74180. }
  74181. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  74182. // offset of the headset from the anchor.
  74183. if (this.webVRCamera.leftCamera) {
  74184. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  74185. this._workingVector.subtractInPlace(this.webVRCamera.position);
  74186. location.subtractToRef(this._workingVector, this._workingVector);
  74187. }
  74188. else {
  74189. this._workingVector.copyFrom(location);
  74190. }
  74191. // Add height to account for user's height offset
  74192. if (this.isInVRMode) {
  74193. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  74194. }
  74195. else {
  74196. this._workingVector.y += this._defaultHeight;
  74197. }
  74198. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  74199. // Create animation from the camera's position to the new location
  74200. this.currentVRCamera.animations = [];
  74201. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74202. var animationCameraTeleportationKeys = [{
  74203. frame: 0,
  74204. value: this.currentVRCamera.position
  74205. },
  74206. {
  74207. frame: 11,
  74208. value: this._workingVector
  74209. }
  74210. ];
  74211. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  74212. animationCameraTeleportation.setEasingFunction(this._circleEase);
  74213. this.currentVRCamera.animations.push(animationCameraTeleportation);
  74214. this._postProcessMove.animations = [];
  74215. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74216. var vignetteWeightKeys = [];
  74217. vignetteWeightKeys.push({
  74218. frame: 0,
  74219. value: 0
  74220. });
  74221. vignetteWeightKeys.push({
  74222. frame: 5,
  74223. value: 8
  74224. });
  74225. vignetteWeightKeys.push({
  74226. frame: 11,
  74227. value: 0
  74228. });
  74229. animationPP.setKeys(vignetteWeightKeys);
  74230. this._postProcessMove.animations.push(animationPP);
  74231. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74232. var vignetteStretchKeys = [];
  74233. vignetteStretchKeys.push({
  74234. frame: 0,
  74235. value: 0
  74236. });
  74237. vignetteStretchKeys.push({
  74238. frame: 5,
  74239. value: 10
  74240. });
  74241. vignetteStretchKeys.push({
  74242. frame: 11,
  74243. value: 0
  74244. });
  74245. animationPP2.setKeys(vignetteStretchKeys);
  74246. this._postProcessMove.animations.push(animationPP2);
  74247. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  74248. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  74249. this._webVRCamera.attachPostProcess(this._postProcessMove);
  74250. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  74251. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  74252. });
  74253. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  74254. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  74255. });
  74256. };
  74257. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  74258. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74259. return;
  74260. }
  74261. var ray;
  74262. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  74263. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  74264. }
  74265. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  74266. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  74267. }
  74268. else {
  74269. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  74270. }
  74271. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  74272. // Moving the gazeTracker on the mesh face targetted
  74273. if (hit && hit.pickedPoint) {
  74274. if (this._displayGaze) {
  74275. var multiplier = 1;
  74276. this._gazeTracker.isVisible = true;
  74277. if (this._isActionableMesh) {
  74278. multiplier = 3;
  74279. }
  74280. this._gazeTracker.scaling.x = hit.distance * multiplier;
  74281. this._gazeTracker.scaling.y = hit.distance * multiplier;
  74282. this._gazeTracker.scaling.z = hit.distance * multiplier;
  74283. var pickNormal = hit.getNormal();
  74284. // To avoid z-fighting
  74285. var deltaFighting = 0.002;
  74286. if (pickNormal) {
  74287. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  74288. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  74289. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  74290. }
  74291. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  74292. if (this._gazeTracker.position.x < 0) {
  74293. this._gazeTracker.position.x += deltaFighting;
  74294. }
  74295. else {
  74296. this._gazeTracker.position.x -= deltaFighting;
  74297. }
  74298. if (this._gazeTracker.position.y < 0) {
  74299. this._gazeTracker.position.y += deltaFighting;
  74300. }
  74301. else {
  74302. this._gazeTracker.position.y -= deltaFighting;
  74303. }
  74304. if (this._gazeTracker.position.z < 0) {
  74305. this._gazeTracker.position.z += deltaFighting;
  74306. }
  74307. else {
  74308. this._gazeTracker.position.z -= deltaFighting;
  74309. }
  74310. }
  74311. // Changing the size of the laser pointer based on the distance from the targetted point
  74312. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  74313. this._rightLaserPointer.scaling.y = hit.distance;
  74314. this._rightLaserPointer.position.z = -hit.distance / 2;
  74315. }
  74316. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  74317. this._leftLaserPointer.scaling.y = hit.distance;
  74318. this._leftLaserPointer.position.z = -hit.distance / 2;
  74319. }
  74320. }
  74321. else {
  74322. this._gazeTracker.isVisible = false;
  74323. }
  74324. if (hit && hit.pickedMesh) {
  74325. this._currentHit = hit;
  74326. if (this._pointerDownOnMeshAsked) {
  74327. this._scene.simulatePointerMove(this._currentHit);
  74328. }
  74329. // The object selected is the floor, we're in a teleportation scenario
  74330. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  74331. // Moving the teleportation area to this targetted point
  74332. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  74333. if (this._currentMeshSelected &&
  74334. !this._isTeleportationFloor(this._currentMeshSelected)) {
  74335. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  74336. }
  74337. this._currentMeshSelected = null;
  74338. this._moveTeleportationSelectorTo(hit);
  74339. return;
  74340. }
  74341. // If not, we're in a selection scenario
  74342. this._hideTeleportationTarget();
  74343. this._teleportationAllowed = false;
  74344. if (hit.pickedMesh !== this._currentMeshSelected) {
  74345. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  74346. this.onNewMeshPicked.notifyObservers(hit);
  74347. this._currentMeshSelected = hit.pickedMesh;
  74348. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  74349. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  74350. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  74351. this._isActionableMesh = true;
  74352. }
  74353. else {
  74354. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74355. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74356. this._isActionableMesh = false;
  74357. }
  74358. try {
  74359. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  74360. }
  74361. catch (err) {
  74362. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  74363. }
  74364. }
  74365. else {
  74366. if (this._currentMeshSelected) {
  74367. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  74368. }
  74369. this._currentMeshSelected = null;
  74370. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74371. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74372. }
  74373. }
  74374. }
  74375. else {
  74376. this._currentHit = null;
  74377. this._currentMeshSelected = null;
  74378. this._teleportationAllowed = false;
  74379. this._hideTeleportationTarget();
  74380. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74381. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74382. }
  74383. };
  74384. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  74385. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  74386. this._leftLaserPointer.material.emissiveColor = color;
  74387. }
  74388. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  74389. this._rightLaserPointer.material.emissiveColor = color;
  74390. }
  74391. };
  74392. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  74393. if (this._gazeTracker.material) {
  74394. this._gazeTracker.material.emissiveColor = color;
  74395. }
  74396. };
  74397. VRExperienceHelper.prototype.dispose = function () {
  74398. if (this.isInVRMode) {
  74399. this.exitVR();
  74400. }
  74401. if (this._passProcessMove) {
  74402. this._passProcessMove.dispose();
  74403. }
  74404. if (this._postProcessMove) {
  74405. this._postProcessMove.dispose();
  74406. }
  74407. if (this._webVRCamera) {
  74408. this._webVRCamera.dispose();
  74409. }
  74410. if (this._vrDeviceOrientationCamera) {
  74411. this._vrDeviceOrientationCamera.dispose();
  74412. }
  74413. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  74414. document.body.removeChild(this._btnVR);
  74415. }
  74416. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  74417. this._deviceOrientationCamera.dispose();
  74418. }
  74419. if (this._gazeTracker) {
  74420. this._gazeTracker.dispose();
  74421. }
  74422. if (this._teleportationTarget) {
  74423. this._teleportationTarget.dispose();
  74424. }
  74425. this._floorMeshesCollection = [];
  74426. document.removeEventListener("keydown", this._onKeyDown);
  74427. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74428. window.removeEventListener("resize", this._onResize);
  74429. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  74430. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  74431. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  74432. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  74433. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  74434. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  74435. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  74436. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74437. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  74438. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  74439. this._scene.unregisterBeforeRender(this.beforeRender);
  74440. };
  74441. VRExperienceHelper.prototype.getClassName = function () {
  74442. return "VRExperienceHelper";
  74443. };
  74444. return VRExperienceHelper;
  74445. }());
  74446. BABYLON.VRExperienceHelper = VRExperienceHelper;
  74447. })(BABYLON || (BABYLON = {}));
  74448. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  74449. // Mainly based on these 2 articles :
  74450. // 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
  74451. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  74452. var BABYLON;
  74453. (function (BABYLON) {
  74454. var JoystickAxis;
  74455. (function (JoystickAxis) {
  74456. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  74457. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  74458. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  74459. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  74460. var VirtualJoystick = /** @class */ (function () {
  74461. function VirtualJoystick(leftJoystick) {
  74462. var _this = this;
  74463. if (leftJoystick) {
  74464. this._leftJoystick = true;
  74465. }
  74466. else {
  74467. this._leftJoystick = false;
  74468. }
  74469. VirtualJoystick._globalJoystickIndex++;
  74470. // By default left & right arrow keys are moving the X
  74471. // and up & down keys are moving the Y
  74472. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74473. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74474. this.reverseLeftRight = false;
  74475. this.reverseUpDown = false;
  74476. // collections of pointers
  74477. this._touches = new BABYLON.StringDictionary();
  74478. this.deltaPosition = BABYLON.Vector3.Zero();
  74479. this._joystickSensibility = 25;
  74480. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74481. this._onResize = function (evt) {
  74482. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74483. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74484. if (VirtualJoystick.vjCanvas) {
  74485. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  74486. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  74487. }
  74488. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  74489. };
  74490. // injecting a canvas element on top of the canvas 3D game
  74491. if (!VirtualJoystick.vjCanvas) {
  74492. window.addEventListener("resize", this._onResize, false);
  74493. VirtualJoystick.vjCanvas = document.createElement("canvas");
  74494. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74495. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74496. VirtualJoystick.vjCanvas.width = window.innerWidth;
  74497. VirtualJoystick.vjCanvas.height = window.innerHeight;
  74498. VirtualJoystick.vjCanvas.style.width = "100%";
  74499. VirtualJoystick.vjCanvas.style.height = "100%";
  74500. VirtualJoystick.vjCanvas.style.position = "absolute";
  74501. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  74502. VirtualJoystick.vjCanvas.style.top = "0px";
  74503. VirtualJoystick.vjCanvas.style.left = "0px";
  74504. VirtualJoystick.vjCanvas.style.zIndex = "5";
  74505. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  74506. // Support for jQuery PEP polyfill
  74507. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  74508. var context = VirtualJoystick.vjCanvas.getContext('2d');
  74509. if (!context) {
  74510. throw new Error("Unable to create canvas for virtual joystick");
  74511. }
  74512. VirtualJoystick.vjCanvasContext = context;
  74513. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  74514. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74515. document.body.appendChild(VirtualJoystick.vjCanvas);
  74516. }
  74517. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  74518. this.pressed = false;
  74519. // default joystick color
  74520. this._joystickColor = "cyan";
  74521. this._joystickPointerID = -1;
  74522. // current joystick position
  74523. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  74524. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  74525. // origin joystick position
  74526. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  74527. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  74528. this._onPointerDownHandlerRef = function (evt) {
  74529. _this._onPointerDown(evt);
  74530. };
  74531. this._onPointerMoveHandlerRef = function (evt) {
  74532. _this._onPointerMove(evt);
  74533. };
  74534. this._onPointerUpHandlerRef = function (evt) {
  74535. _this._onPointerUp(evt);
  74536. };
  74537. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  74538. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  74539. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  74540. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  74541. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  74542. evt.preventDefault(); // Disables system menu
  74543. }, false);
  74544. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74545. }
  74546. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  74547. this._joystickSensibility = newJoystickSensibility;
  74548. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74549. };
  74550. VirtualJoystick.prototype._onPointerDown = function (e) {
  74551. var positionOnScreenCondition;
  74552. e.preventDefault();
  74553. if (this._leftJoystick === true) {
  74554. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  74555. }
  74556. else {
  74557. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  74558. }
  74559. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  74560. // First contact will be dedicated to the virtual joystick
  74561. this._joystickPointerID = e.pointerId;
  74562. this._joystickPointerStartPos.x = e.clientX;
  74563. this._joystickPointerStartPos.y = e.clientY;
  74564. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  74565. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  74566. this._deltaJoystickVector.x = 0;
  74567. this._deltaJoystickVector.y = 0;
  74568. this.pressed = true;
  74569. this._touches.add(e.pointerId.toString(), e);
  74570. }
  74571. else {
  74572. // You can only trigger the action buttons with a joystick declared
  74573. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  74574. this._action();
  74575. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  74576. }
  74577. }
  74578. };
  74579. VirtualJoystick.prototype._onPointerMove = function (e) {
  74580. // If the current pointer is the one associated to the joystick (first touch contact)
  74581. if (this._joystickPointerID == e.pointerId) {
  74582. this._joystickPointerPos.x = e.clientX;
  74583. this._joystickPointerPos.y = e.clientY;
  74584. this._deltaJoystickVector = this._joystickPointerPos.clone();
  74585. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  74586. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  74587. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  74588. switch (this._axisTargetedByLeftAndRight) {
  74589. case JoystickAxis.X:
  74590. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  74591. break;
  74592. case JoystickAxis.Y:
  74593. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  74594. break;
  74595. case JoystickAxis.Z:
  74596. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  74597. break;
  74598. }
  74599. var directionUpDown = this.reverseUpDown ? 1 : -1;
  74600. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  74601. switch (this._axisTargetedByUpAndDown) {
  74602. case JoystickAxis.X:
  74603. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  74604. break;
  74605. case JoystickAxis.Y:
  74606. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  74607. break;
  74608. case JoystickAxis.Z:
  74609. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  74610. break;
  74611. }
  74612. }
  74613. else {
  74614. var data = this._touches.get(e.pointerId.toString());
  74615. if (data) {
  74616. data.x = e.clientX;
  74617. data.y = e.clientY;
  74618. }
  74619. }
  74620. };
  74621. VirtualJoystick.prototype._onPointerUp = function (e) {
  74622. if (this._joystickPointerID == e.pointerId) {
  74623. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  74624. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  74625. this._joystickPointerID = -1;
  74626. this.pressed = false;
  74627. }
  74628. else {
  74629. var touch = this._touches.get(e.pointerId.toString());
  74630. if (touch) {
  74631. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74632. }
  74633. }
  74634. this._deltaJoystickVector.x = 0;
  74635. this._deltaJoystickVector.y = 0;
  74636. this._touches.remove(e.pointerId.toString());
  74637. };
  74638. /**
  74639. * Change the color of the virtual joystick
  74640. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  74641. */
  74642. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  74643. this._joystickColor = newColor;
  74644. };
  74645. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  74646. this._action = action;
  74647. };
  74648. // Define which axis you'd like to control for left & right
  74649. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  74650. switch (axis) {
  74651. case JoystickAxis.X:
  74652. case JoystickAxis.Y:
  74653. case JoystickAxis.Z:
  74654. this._axisTargetedByLeftAndRight = axis;
  74655. break;
  74656. default:
  74657. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74658. break;
  74659. }
  74660. };
  74661. // Define which axis you'd like to control for up & down
  74662. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  74663. switch (axis) {
  74664. case JoystickAxis.X:
  74665. case JoystickAxis.Y:
  74666. case JoystickAxis.Z:
  74667. this._axisTargetedByUpAndDown = axis;
  74668. break;
  74669. default:
  74670. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74671. break;
  74672. }
  74673. };
  74674. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  74675. var _this = this;
  74676. if (this.pressed) {
  74677. this._touches.forEach(function (key, touch) {
  74678. if (touch.pointerId === _this._joystickPointerID) {
  74679. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  74680. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  74681. VirtualJoystick.vjCanvasContext.beginPath();
  74682. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74683. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74684. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  74685. VirtualJoystick.vjCanvasContext.stroke();
  74686. VirtualJoystick.vjCanvasContext.closePath();
  74687. VirtualJoystick.vjCanvasContext.beginPath();
  74688. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74689. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74690. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  74691. VirtualJoystick.vjCanvasContext.stroke();
  74692. VirtualJoystick.vjCanvasContext.closePath();
  74693. VirtualJoystick.vjCanvasContext.beginPath();
  74694. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74695. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  74696. VirtualJoystick.vjCanvasContext.stroke();
  74697. VirtualJoystick.vjCanvasContext.closePath();
  74698. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  74699. }
  74700. else {
  74701. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74702. VirtualJoystick.vjCanvasContext.beginPath();
  74703. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  74704. VirtualJoystick.vjCanvasContext.beginPath();
  74705. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  74706. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74707. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  74708. VirtualJoystick.vjCanvasContext.stroke();
  74709. VirtualJoystick.vjCanvasContext.closePath();
  74710. touch.prevX = touch.x;
  74711. touch.prevY = touch.y;
  74712. }
  74713. ;
  74714. });
  74715. }
  74716. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74717. };
  74718. VirtualJoystick.prototype.releaseCanvas = function () {
  74719. if (VirtualJoystick.vjCanvas) {
  74720. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  74721. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  74722. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  74723. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  74724. window.removeEventListener("resize", this._onResize);
  74725. document.body.removeChild(VirtualJoystick.vjCanvas);
  74726. VirtualJoystick.vjCanvas = null;
  74727. }
  74728. };
  74729. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  74730. VirtualJoystick._globalJoystickIndex = 0;
  74731. return VirtualJoystick;
  74732. }());
  74733. BABYLON.VirtualJoystick = VirtualJoystick;
  74734. })(BABYLON || (BABYLON = {}));
  74735. //# sourceMappingURL=babylon.virtualJoystick.js.map
  74736. var BABYLON;
  74737. (function (BABYLON) {
  74738. // We're mainly based on the logic defined into the FreeCamera code
  74739. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  74740. __extends(VirtualJoysticksCamera, _super);
  74741. function VirtualJoysticksCamera(name, position, scene) {
  74742. var _this = _super.call(this, name, position, scene) || this;
  74743. _this.inputs.addVirtualJoystick();
  74744. return _this;
  74745. }
  74746. VirtualJoysticksCamera.prototype.getClassName = function () {
  74747. return "VirtualJoysticksCamera";
  74748. };
  74749. return VirtualJoysticksCamera;
  74750. }(BABYLON.FreeCamera));
  74751. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  74752. })(BABYLON || (BABYLON = {}));
  74753. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  74754. var BABYLON;
  74755. (function (BABYLON) {
  74756. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  74757. function FreeCameraVirtualJoystickInput() {
  74758. }
  74759. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  74760. return this._leftjoystick;
  74761. };
  74762. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  74763. return this._rightjoystick;
  74764. };
  74765. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  74766. if (this._leftjoystick) {
  74767. var camera = this.camera;
  74768. var speed = camera._computeLocalCameraSpeed() * 50;
  74769. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  74770. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  74771. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  74772. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  74773. if (!this._leftjoystick.pressed) {
  74774. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  74775. }
  74776. if (!this._rightjoystick.pressed) {
  74777. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  74778. }
  74779. }
  74780. };
  74781. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  74782. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  74783. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  74784. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  74785. this._leftjoystick.setJoystickSensibility(0.15);
  74786. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  74787. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  74788. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  74789. this._rightjoystick.reverseUpDown = true;
  74790. this._rightjoystick.setJoystickSensibility(0.05);
  74791. this._rightjoystick.setJoystickColor("yellow");
  74792. };
  74793. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  74794. this._leftjoystick.releaseCanvas();
  74795. this._rightjoystick.releaseCanvas();
  74796. };
  74797. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  74798. return "FreeCameraVirtualJoystickInput";
  74799. };
  74800. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  74801. return "virtualJoystick";
  74802. };
  74803. return FreeCameraVirtualJoystickInput;
  74804. }());
  74805. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  74806. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  74807. })(BABYLON || (BABYLON = {}));
  74808. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  74809. var BABYLON;
  74810. (function (BABYLON) {
  74811. var SimplificationSettings = /** @class */ (function () {
  74812. function SimplificationSettings(quality, distance, optimizeMesh) {
  74813. this.quality = quality;
  74814. this.distance = distance;
  74815. this.optimizeMesh = optimizeMesh;
  74816. }
  74817. return SimplificationSettings;
  74818. }());
  74819. BABYLON.SimplificationSettings = SimplificationSettings;
  74820. var SimplificationQueue = /** @class */ (function () {
  74821. function SimplificationQueue() {
  74822. this.running = false;
  74823. this._simplificationArray = [];
  74824. }
  74825. SimplificationQueue.prototype.addTask = function (task) {
  74826. this._simplificationArray.push(task);
  74827. };
  74828. SimplificationQueue.prototype.executeNext = function () {
  74829. var task = this._simplificationArray.pop();
  74830. if (task) {
  74831. this.running = true;
  74832. this.runSimplification(task);
  74833. }
  74834. else {
  74835. this.running = false;
  74836. }
  74837. };
  74838. SimplificationQueue.prototype.runSimplification = function (task) {
  74839. var _this = this;
  74840. if (task.parallelProcessing) {
  74841. //parallel simplifier
  74842. task.settings.forEach(function (setting) {
  74843. var simplifier = _this.getSimplifier(task);
  74844. simplifier.simplify(setting, function (newMesh) {
  74845. task.mesh.addLODLevel(setting.distance, newMesh);
  74846. newMesh.isVisible = true;
  74847. //check if it is the last
  74848. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  74849. //all done, run the success callback.
  74850. task.successCallback();
  74851. }
  74852. _this.executeNext();
  74853. });
  74854. });
  74855. }
  74856. else {
  74857. //single simplifier.
  74858. var simplifier = this.getSimplifier(task);
  74859. var runDecimation = function (setting, callback) {
  74860. simplifier.simplify(setting, function (newMesh) {
  74861. task.mesh.addLODLevel(setting.distance, newMesh);
  74862. newMesh.isVisible = true;
  74863. //run the next quality level
  74864. callback();
  74865. });
  74866. };
  74867. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  74868. runDecimation(task.settings[loop.index], function () {
  74869. loop.executeNext();
  74870. });
  74871. }, function () {
  74872. //execution ended, run the success callback.
  74873. if (task.successCallback) {
  74874. task.successCallback();
  74875. }
  74876. _this.executeNext();
  74877. });
  74878. }
  74879. };
  74880. SimplificationQueue.prototype.getSimplifier = function (task) {
  74881. switch (task.simplificationType) {
  74882. case SimplificationType.QUADRATIC:
  74883. default:
  74884. return new QuadraticErrorSimplification(task.mesh);
  74885. }
  74886. };
  74887. return SimplificationQueue;
  74888. }());
  74889. BABYLON.SimplificationQueue = SimplificationQueue;
  74890. /**
  74891. * The implemented types of simplification.
  74892. * At the moment only Quadratic Error Decimation is implemented.
  74893. */
  74894. var SimplificationType;
  74895. (function (SimplificationType) {
  74896. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  74897. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  74898. var DecimationTriangle = /** @class */ (function () {
  74899. function DecimationTriangle(vertices) {
  74900. this.vertices = vertices;
  74901. this.error = new Array(4);
  74902. this.deleted = false;
  74903. this.isDirty = false;
  74904. this.deletePending = false;
  74905. this.borderFactor = 0;
  74906. }
  74907. return DecimationTriangle;
  74908. }());
  74909. BABYLON.DecimationTriangle = DecimationTriangle;
  74910. var DecimationVertex = /** @class */ (function () {
  74911. function DecimationVertex(position, id) {
  74912. this.position = position;
  74913. this.id = id;
  74914. this.isBorder = true;
  74915. this.q = new QuadraticMatrix();
  74916. this.triangleCount = 0;
  74917. this.triangleStart = 0;
  74918. this.originalOffsets = [];
  74919. }
  74920. DecimationVertex.prototype.updatePosition = function (newPosition) {
  74921. this.position.copyFrom(newPosition);
  74922. };
  74923. return DecimationVertex;
  74924. }());
  74925. BABYLON.DecimationVertex = DecimationVertex;
  74926. var QuadraticMatrix = /** @class */ (function () {
  74927. function QuadraticMatrix(data) {
  74928. this.data = new Array(10);
  74929. for (var i = 0; i < 10; ++i) {
  74930. if (data && data[i]) {
  74931. this.data[i] = data[i];
  74932. }
  74933. else {
  74934. this.data[i] = 0;
  74935. }
  74936. }
  74937. }
  74938. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  74939. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  74940. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  74941. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  74942. return det;
  74943. };
  74944. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  74945. for (var i = 0; i < 10; ++i) {
  74946. this.data[i] += matrix.data[i];
  74947. }
  74948. };
  74949. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  74950. for (var i = 0; i < 10; ++i) {
  74951. this.data[i] += data[i];
  74952. }
  74953. };
  74954. QuadraticMatrix.prototype.add = function (matrix) {
  74955. var m = new QuadraticMatrix();
  74956. for (var i = 0; i < 10; ++i) {
  74957. m.data[i] = this.data[i] + matrix.data[i];
  74958. }
  74959. return m;
  74960. };
  74961. QuadraticMatrix.FromData = function (a, b, c, d) {
  74962. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  74963. };
  74964. //returning an array to avoid garbage collection
  74965. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  74966. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  74967. };
  74968. return QuadraticMatrix;
  74969. }());
  74970. BABYLON.QuadraticMatrix = QuadraticMatrix;
  74971. var Reference = /** @class */ (function () {
  74972. function Reference(vertexId, triangleId) {
  74973. this.vertexId = vertexId;
  74974. this.triangleId = triangleId;
  74975. }
  74976. return Reference;
  74977. }());
  74978. BABYLON.Reference = Reference;
  74979. /**
  74980. * An implementation of the Quadratic Error simplification algorithm.
  74981. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  74982. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  74983. * @author RaananW
  74984. */
  74985. var QuadraticErrorSimplification = /** @class */ (function () {
  74986. function QuadraticErrorSimplification(_mesh) {
  74987. this._mesh = _mesh;
  74988. this.syncIterations = 5000;
  74989. this.aggressiveness = 7;
  74990. this.decimationIterations = 100;
  74991. this.boundingBoxEpsilon = BABYLON.Epsilon;
  74992. }
  74993. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  74994. var _this = this;
  74995. this.initDecimatedMesh();
  74996. //iterating through the submeshes array, one after the other.
  74997. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  74998. _this.initWithMesh(loop.index, function () {
  74999. _this.runDecimation(settings, loop.index, function () {
  75000. loop.executeNext();
  75001. });
  75002. }, settings.optimizeMesh);
  75003. }, function () {
  75004. setTimeout(function () {
  75005. successCallback(_this._reconstructedMesh);
  75006. }, 0);
  75007. });
  75008. };
  75009. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  75010. var _this = this;
  75011. var targetCount = ~~(this.triangles.length * settings.quality);
  75012. var deletedTriangles = 0;
  75013. var triangleCount = this.triangles.length;
  75014. var iterationFunction = function (iteration, callback) {
  75015. setTimeout(function () {
  75016. if (iteration % 5 === 0) {
  75017. _this.updateMesh(iteration === 0);
  75018. }
  75019. for (var i = 0; i < _this.triangles.length; ++i) {
  75020. _this.triangles[i].isDirty = false;
  75021. }
  75022. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  75023. var trianglesIterator = function (i) {
  75024. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  75025. var t = _this.triangles[tIdx];
  75026. if (!t)
  75027. return;
  75028. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  75029. return;
  75030. }
  75031. for (var j = 0; j < 3; ++j) {
  75032. if (t.error[j] < threshold) {
  75033. var deleted0 = [];
  75034. var deleted1 = [];
  75035. var v0 = t.vertices[j];
  75036. var v1 = t.vertices[(j + 1) % 3];
  75037. if (v0.isBorder || v1.isBorder)
  75038. continue;
  75039. var p = BABYLON.Vector3.Zero();
  75040. var n = BABYLON.Vector3.Zero();
  75041. var uv = BABYLON.Vector2.Zero();
  75042. var color = new BABYLON.Color4(0, 0, 0, 1);
  75043. _this.calculateError(v0, v1, p, n, uv, color);
  75044. var delTr = new Array();
  75045. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  75046. continue;
  75047. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  75048. continue;
  75049. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  75050. continue;
  75051. var uniqueArray = new Array();
  75052. delTr.forEach(function (deletedT) {
  75053. if (uniqueArray.indexOf(deletedT) === -1) {
  75054. deletedT.deletePending = true;
  75055. uniqueArray.push(deletedT);
  75056. }
  75057. });
  75058. if (uniqueArray.length % 2 !== 0) {
  75059. continue;
  75060. }
  75061. v0.q = v1.q.add(v0.q);
  75062. v0.updatePosition(p);
  75063. var tStart = _this.references.length;
  75064. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  75065. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  75066. var tCount = _this.references.length - tStart;
  75067. if (tCount <= v0.triangleCount) {
  75068. if (tCount) {
  75069. for (var c = 0; c < tCount; c++) {
  75070. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  75071. }
  75072. }
  75073. }
  75074. else {
  75075. v0.triangleStart = tStart;
  75076. }
  75077. v0.triangleCount = tCount;
  75078. break;
  75079. }
  75080. }
  75081. };
  75082. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  75083. }, 0);
  75084. };
  75085. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  75086. if (triangleCount - deletedTriangles <= targetCount)
  75087. loop.breakLoop();
  75088. else {
  75089. iterationFunction(loop.index, function () {
  75090. loop.executeNext();
  75091. });
  75092. }
  75093. }, function () {
  75094. setTimeout(function () {
  75095. //reconstruct this part of the mesh
  75096. _this.reconstructMesh(submeshIndex);
  75097. successCallback();
  75098. }, 0);
  75099. });
  75100. };
  75101. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  75102. var _this = this;
  75103. this.vertices = [];
  75104. this.triangles = [];
  75105. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  75106. var indices = this._mesh.getIndices();
  75107. var submesh = this._mesh.subMeshes[submeshIndex];
  75108. var findInVertices = function (positionToSearch) {
  75109. if (optimizeMesh) {
  75110. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  75111. if (_this.vertices[ii].position.equals(positionToSearch)) {
  75112. return _this.vertices[ii];
  75113. }
  75114. }
  75115. }
  75116. return null;
  75117. };
  75118. var vertexReferences = [];
  75119. var vertexInit = function (i) {
  75120. if (!positionData) {
  75121. return;
  75122. }
  75123. var offset = i + submesh.verticesStart;
  75124. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  75125. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  75126. vertex.originalOffsets.push(offset);
  75127. if (vertex.id === _this.vertices.length) {
  75128. _this.vertices.push(vertex);
  75129. }
  75130. vertexReferences.push(vertex.id);
  75131. };
  75132. //var totalVertices = mesh.getTotalVertices();
  75133. var totalVertices = submesh.verticesCount;
  75134. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  75135. var indicesInit = function (i) {
  75136. if (!indices) {
  75137. return;
  75138. }
  75139. var offset = (submesh.indexStart / 3) + i;
  75140. var pos = (offset * 3);
  75141. var i0 = indices[pos + 0];
  75142. var i1 = indices[pos + 1];
  75143. var i2 = indices[pos + 2];
  75144. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  75145. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  75146. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  75147. var triangle = new DecimationTriangle([v0, v1, v2]);
  75148. triangle.originalOffset = pos;
  75149. _this.triangles.push(triangle);
  75150. };
  75151. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  75152. _this.init(callback);
  75153. });
  75154. });
  75155. };
  75156. QuadraticErrorSimplification.prototype.init = function (callback) {
  75157. var _this = this;
  75158. var triangleInit1 = function (i) {
  75159. var t = _this.triangles[i];
  75160. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  75161. for (var j = 0; j < 3; j++) {
  75162. 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))));
  75163. }
  75164. };
  75165. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  75166. var triangleInit2 = function (i) {
  75167. var t = _this.triangles[i];
  75168. for (var j = 0; j < 3; ++j) {
  75169. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  75170. }
  75171. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  75172. };
  75173. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  75174. callback();
  75175. });
  75176. });
  75177. };
  75178. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  75179. var newTriangles = [];
  75180. var i;
  75181. for (i = 0; i < this.vertices.length; ++i) {
  75182. this.vertices[i].triangleCount = 0;
  75183. }
  75184. var t;
  75185. var j;
  75186. for (i = 0; i < this.triangles.length; ++i) {
  75187. if (!this.triangles[i].deleted) {
  75188. t = this.triangles[i];
  75189. for (j = 0; j < 3; ++j) {
  75190. t.vertices[j].triangleCount = 1;
  75191. }
  75192. newTriangles.push(t);
  75193. }
  75194. }
  75195. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  75196. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  75197. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  75198. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  75199. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  75200. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75201. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  75202. var vertexCount = 0;
  75203. for (i = 0; i < this.vertices.length; ++i) {
  75204. var vertex = this.vertices[i];
  75205. vertex.id = vertexCount;
  75206. if (vertex.triangleCount) {
  75207. vertex.originalOffsets.forEach(function (originalOffset) {
  75208. if (!normalData) {
  75209. return;
  75210. }
  75211. newPositionData.push(vertex.position.x);
  75212. newPositionData.push(vertex.position.y);
  75213. newPositionData.push(vertex.position.z);
  75214. newNormalData.push(normalData[originalOffset * 3]);
  75215. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  75216. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  75217. if (uvs && uvs.length) {
  75218. newUVsData.push(uvs[(originalOffset * 2)]);
  75219. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  75220. }
  75221. else if (colorsData && colorsData.length) {
  75222. newColorsData.push(colorsData[(originalOffset * 4)]);
  75223. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  75224. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  75225. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  75226. }
  75227. ++vertexCount;
  75228. });
  75229. }
  75230. }
  75231. var startingIndex = this._reconstructedMesh.getTotalIndices();
  75232. var startingVertex = this._reconstructedMesh.getTotalVertices();
  75233. var submeshesArray = this._reconstructedMesh.subMeshes;
  75234. this._reconstructedMesh.subMeshes = [];
  75235. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  75236. var originalIndices = this._mesh.getIndices();
  75237. for (i = 0; i < newTriangles.length; ++i) {
  75238. t = newTriangles[i]; //now get the new referencing point for each vertex
  75239. [0, 1, 2].forEach(function (idx) {
  75240. var id = originalIndices[t.originalOffset + idx];
  75241. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  75242. if (offset < 0)
  75243. offset = 0;
  75244. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  75245. });
  75246. }
  75247. //overwriting the old vertex buffers and indices.
  75248. this._reconstructedMesh.setIndices(newIndicesArray);
  75249. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  75250. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  75251. if (newUVsData.length > 0)
  75252. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  75253. if (newColorsData.length > 0)
  75254. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  75255. //create submesh
  75256. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  75257. if (submeshIndex > 0) {
  75258. this._reconstructedMesh.subMeshes = [];
  75259. submeshesArray.forEach(function (submesh) {
  75260. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  75261. });
  75262. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  75263. }
  75264. };
  75265. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  75266. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  75267. this._reconstructedMesh.material = this._mesh.material;
  75268. this._reconstructedMesh.parent = this._mesh.parent;
  75269. this._reconstructedMesh.isVisible = false;
  75270. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  75271. };
  75272. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  75273. for (var i = 0; i < vertex1.triangleCount; ++i) {
  75274. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  75275. if (t.deleted)
  75276. continue;
  75277. var s = this.references[vertex1.triangleStart + i].vertexId;
  75278. var v1 = t.vertices[(s + 1) % 3];
  75279. var v2 = t.vertices[(s + 2) % 3];
  75280. if ((v1 === vertex2 || v2 === vertex2)) {
  75281. deletedArray[i] = true;
  75282. delTr.push(t);
  75283. continue;
  75284. }
  75285. var d1 = v1.position.subtract(point);
  75286. d1 = d1.normalize();
  75287. var d2 = v2.position.subtract(point);
  75288. d2 = d2.normalize();
  75289. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  75290. return true;
  75291. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  75292. deletedArray[i] = false;
  75293. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  75294. return true;
  75295. }
  75296. return false;
  75297. };
  75298. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  75299. var newDeleted = deletedTriangles;
  75300. for (var i = 0; i < vertex.triangleCount; ++i) {
  75301. var ref = this.references[vertex.triangleStart + i];
  75302. var t = this.triangles[ref.triangleId];
  75303. if (t.deleted)
  75304. continue;
  75305. if (deletedArray[i] && t.deletePending) {
  75306. t.deleted = true;
  75307. newDeleted++;
  75308. continue;
  75309. }
  75310. t.vertices[ref.vertexId] = origVertex;
  75311. t.isDirty = true;
  75312. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  75313. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  75314. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  75315. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  75316. this.references.push(ref);
  75317. }
  75318. return newDeleted;
  75319. };
  75320. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  75321. for (var i = 0; i < this.vertices.length; ++i) {
  75322. var vCount = [];
  75323. var vId = [];
  75324. var v = this.vertices[i];
  75325. var j;
  75326. for (j = 0; j < v.triangleCount; ++j) {
  75327. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  75328. for (var ii = 0; ii < 3; ii++) {
  75329. var ofs = 0;
  75330. var vv = triangle.vertices[ii];
  75331. while (ofs < vCount.length) {
  75332. if (vId[ofs] === vv.id)
  75333. break;
  75334. ++ofs;
  75335. }
  75336. if (ofs === vCount.length) {
  75337. vCount.push(1);
  75338. vId.push(vv.id);
  75339. }
  75340. else {
  75341. vCount[ofs]++;
  75342. }
  75343. }
  75344. }
  75345. for (j = 0; j < vCount.length; ++j) {
  75346. if (vCount[j] === 1) {
  75347. this.vertices[vId[j]].isBorder = true;
  75348. }
  75349. else {
  75350. this.vertices[vId[j]].isBorder = false;
  75351. }
  75352. }
  75353. }
  75354. };
  75355. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  75356. if (identifyBorders === void 0) { identifyBorders = false; }
  75357. var i;
  75358. if (!identifyBorders) {
  75359. var newTrianglesVector = [];
  75360. for (i = 0; i < this.triangles.length; ++i) {
  75361. if (!this.triangles[i].deleted) {
  75362. newTrianglesVector.push(this.triangles[i]);
  75363. }
  75364. }
  75365. this.triangles = newTrianglesVector;
  75366. }
  75367. for (i = 0; i < this.vertices.length; ++i) {
  75368. this.vertices[i].triangleCount = 0;
  75369. this.vertices[i].triangleStart = 0;
  75370. }
  75371. var t;
  75372. var j;
  75373. var v;
  75374. for (i = 0; i < this.triangles.length; ++i) {
  75375. t = this.triangles[i];
  75376. for (j = 0; j < 3; ++j) {
  75377. v = t.vertices[j];
  75378. v.triangleCount++;
  75379. }
  75380. }
  75381. var tStart = 0;
  75382. for (i = 0; i < this.vertices.length; ++i) {
  75383. this.vertices[i].triangleStart = tStart;
  75384. tStart += this.vertices[i].triangleCount;
  75385. this.vertices[i].triangleCount = 0;
  75386. }
  75387. var newReferences = new Array(this.triangles.length * 3);
  75388. for (i = 0; i < this.triangles.length; ++i) {
  75389. t = this.triangles[i];
  75390. for (j = 0; j < 3; ++j) {
  75391. v = t.vertices[j];
  75392. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  75393. v.triangleCount++;
  75394. }
  75395. }
  75396. this.references = newReferences;
  75397. if (identifyBorders) {
  75398. this.identifyBorder();
  75399. }
  75400. };
  75401. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  75402. var x = point.x;
  75403. var y = point.y;
  75404. var z = point.z;
  75405. 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
  75406. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  75407. };
  75408. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  75409. var q = vertex1.q.add(vertex2.q);
  75410. var border = vertex1.isBorder && vertex2.isBorder;
  75411. var error = 0;
  75412. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  75413. if (qDet !== 0 && !border) {
  75414. if (!pointResult) {
  75415. pointResult = BABYLON.Vector3.Zero();
  75416. }
  75417. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  75418. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  75419. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  75420. error = this.vertexError(q, pointResult);
  75421. }
  75422. else {
  75423. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  75424. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  75425. var error1 = this.vertexError(q, vertex1.position);
  75426. var error2 = this.vertexError(q, vertex2.position);
  75427. var error3 = this.vertexError(q, p3);
  75428. error = Math.min(error1, error2, error3);
  75429. if (error === error1) {
  75430. if (pointResult) {
  75431. pointResult.copyFrom(vertex1.position);
  75432. }
  75433. }
  75434. else if (error === error2) {
  75435. if (pointResult) {
  75436. pointResult.copyFrom(vertex2.position);
  75437. }
  75438. }
  75439. else {
  75440. if (pointResult) {
  75441. pointResult.copyFrom(p3);
  75442. }
  75443. }
  75444. }
  75445. return error;
  75446. };
  75447. return QuadraticErrorSimplification;
  75448. }());
  75449. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  75450. })(BABYLON || (BABYLON = {}));
  75451. //# sourceMappingURL=babylon.meshSimplification.js.map
  75452. var BABYLON;
  75453. (function (BABYLON) {
  75454. var MeshLODLevel = /** @class */ (function () {
  75455. function MeshLODLevel(distance, mesh) {
  75456. this.distance = distance;
  75457. this.mesh = mesh;
  75458. }
  75459. return MeshLODLevel;
  75460. }());
  75461. BABYLON.MeshLODLevel = MeshLODLevel;
  75462. })(BABYLON || (BABYLON = {}));
  75463. //# sourceMappingURL=babylon.meshLODLevel.js.map
  75464. var BABYLON;
  75465. (function (BABYLON) {
  75466. /**
  75467. * Defines the root class used to create scene optimization to use with SceneOptimizer
  75468. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75469. */
  75470. var SceneOptimization = /** @class */ (function () {
  75471. /**
  75472. * Creates the SceneOptimization object
  75473. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75474. * @param desc defines the description associated with the optimization
  75475. */
  75476. function SceneOptimization(priority) {
  75477. if (priority === void 0) { priority = 0; }
  75478. this.priority = priority;
  75479. }
  75480. /**
  75481. * Gets a string describing the action executed by the current optimization
  75482. */
  75483. SceneOptimization.prototype.getDescription = function () {
  75484. return "";
  75485. };
  75486. /**
  75487. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75488. * @param scene defines the current scene where to apply this optimization
  75489. * @returnstrue if everything that can be done was applied
  75490. */
  75491. SceneOptimization.prototype.apply = function (scene) {
  75492. return true;
  75493. };
  75494. ;
  75495. return SceneOptimization;
  75496. }());
  75497. BABYLON.SceneOptimization = SceneOptimization;
  75498. /**
  75499. * Defines an optimization used to reduce the size of render target textures
  75500. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75501. */
  75502. var TextureOptimization = /** @class */ (function (_super) {
  75503. __extends(TextureOptimization, _super);
  75504. /**
  75505. * Creates the TextureOptimization object
  75506. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75507. * @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
  75508. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  75509. */
  75510. function TextureOptimization(priority, maximumSize, step) {
  75511. if (priority === void 0) { priority = 0; }
  75512. if (maximumSize === void 0) { maximumSize = 1024; }
  75513. if (step === void 0) { step = 0.5; }
  75514. var _this = _super.call(this, priority) || this;
  75515. _this.priority = priority;
  75516. _this.maximumSize = maximumSize;
  75517. _this.step = step;
  75518. return _this;
  75519. }
  75520. /**
  75521. * Gets a string describing the action executed by the current optimization
  75522. */
  75523. TextureOptimization.prototype.getDescription = function () {
  75524. return "Reducing render target texture size to " + this.maximumSize;
  75525. };
  75526. /**
  75527. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75528. * @param scene defines the current scene where to apply this optimization
  75529. */
  75530. TextureOptimization.prototype.apply = function (scene) {
  75531. var allDone = true;
  75532. for (var index = 0; index < scene.textures.length; index++) {
  75533. var texture = scene.textures[index];
  75534. if (!texture.canRescale || texture.getContext) {
  75535. continue;
  75536. }
  75537. var currentSize = texture.getSize();
  75538. var maxDimension = Math.max(currentSize.width, currentSize.height);
  75539. if (maxDimension > this.maximumSize) {
  75540. texture.scale(this.step);
  75541. allDone = false;
  75542. }
  75543. }
  75544. return allDone;
  75545. };
  75546. return TextureOptimization;
  75547. }(SceneOptimization));
  75548. BABYLON.TextureOptimization = TextureOptimization;
  75549. /**
  75550. * Defines an optimization used to increase or decrease the rendering resolution
  75551. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75552. */
  75553. var HardwareScalingOptimization = /** @class */ (function (_super) {
  75554. __extends(HardwareScalingOptimization, _super);
  75555. /**
  75556. * Creates the HardwareScalingOptimization object
  75557. * @param priority priority defines the priority of this optimization (0 by default which means first in the list)
  75558. * @param maximumScale
  75559. * @param step
  75560. */
  75561. function HardwareScalingOptimization(priority, maximumScale, step) {
  75562. if (priority === void 0) { priority = 0; }
  75563. if (maximumScale === void 0) { maximumScale = 2; }
  75564. if (step === void 0) { step = 0.25; }
  75565. var _this = _super.call(this, priority) || this;
  75566. _this.priority = priority;
  75567. _this.maximumScale = maximumScale;
  75568. _this.step = step;
  75569. _this._currentScale = -1;
  75570. _this._directionOffset = 1;
  75571. return _this;
  75572. }
  75573. /**
  75574. * Gets a string describing the action executed by the current optimization
  75575. */
  75576. HardwareScalingOptimization.prototype.getDescription = function () {
  75577. return "Setting hardware scaling level to " + this._currentScale;
  75578. };
  75579. /**
  75580. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75581. * @param scene defines the current scene where to apply this optimization
  75582. */
  75583. HardwareScalingOptimization.prototype.apply = function (scene) {
  75584. if (this._currentScale === -1) {
  75585. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  75586. if (this._currentScale > this.maximumScale) {
  75587. this._directionOffset = -1;
  75588. }
  75589. }
  75590. this._currentScale += this._directionOffset * this.step;
  75591. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  75592. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  75593. };
  75594. ;
  75595. return HardwareScalingOptimization;
  75596. }(SceneOptimization));
  75597. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  75598. /**
  75599. * Defines an optimization used to remove shadows
  75600. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75601. */
  75602. var ShadowsOptimization = /** @class */ (function (_super) {
  75603. __extends(ShadowsOptimization, _super);
  75604. function ShadowsOptimization() {
  75605. return _super !== null && _super.apply(this, arguments) || this;
  75606. }
  75607. /**
  75608. * Gets a string describing the action executed by the current optimization
  75609. */
  75610. ShadowsOptimization.prototype.getDescription = function () {
  75611. return "Turning shadows off";
  75612. };
  75613. /**
  75614. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75615. * @param scene defines the current scene where to apply this optimization
  75616. */
  75617. ShadowsOptimization.prototype.apply = function (scene) {
  75618. scene.shadowsEnabled = false;
  75619. return true;
  75620. };
  75621. ;
  75622. return ShadowsOptimization;
  75623. }(SceneOptimization));
  75624. BABYLON.ShadowsOptimization = ShadowsOptimization;
  75625. /**
  75626. * Defines an optimization used to turn post-processes off
  75627. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75628. */
  75629. var PostProcessesOptimization = /** @class */ (function (_super) {
  75630. __extends(PostProcessesOptimization, _super);
  75631. function PostProcessesOptimization() {
  75632. return _super !== null && _super.apply(this, arguments) || this;
  75633. }
  75634. /**
  75635. * Gets a string describing the action executed by the current optimization
  75636. */
  75637. PostProcessesOptimization.prototype.getDescription = function () {
  75638. return "Turning post-processes off";
  75639. };
  75640. /**
  75641. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75642. * @param scene defines the current scene where to apply this optimization
  75643. */
  75644. PostProcessesOptimization.prototype.apply = function (scene) {
  75645. scene.postProcessesEnabled = false;
  75646. return true;
  75647. };
  75648. ;
  75649. return PostProcessesOptimization;
  75650. }(SceneOptimization));
  75651. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  75652. /**
  75653. * Defines an optimization used to turn lens flares off
  75654. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75655. */
  75656. var LensFlaresOptimization = /** @class */ (function (_super) {
  75657. __extends(LensFlaresOptimization, _super);
  75658. function LensFlaresOptimization() {
  75659. return _super !== null && _super.apply(this, arguments) || this;
  75660. }
  75661. /**
  75662. * Gets a string describing the action executed by the current optimization
  75663. */
  75664. LensFlaresOptimization.prototype.getDescription = function () {
  75665. return "Turning lens flares off";
  75666. };
  75667. /**
  75668. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75669. * @param scene defines the current scene where to apply this optimization
  75670. */
  75671. LensFlaresOptimization.prototype.apply = function (scene) {
  75672. scene.lensFlaresEnabled = false;
  75673. return true;
  75674. };
  75675. ;
  75676. return LensFlaresOptimization;
  75677. }(SceneOptimization));
  75678. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  75679. /**
  75680. * Defines an optimization based on user defined callback.
  75681. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75682. */
  75683. var CustomOptimization = /** @class */ (function (_super) {
  75684. __extends(CustomOptimization, _super);
  75685. function CustomOptimization() {
  75686. return _super !== null && _super.apply(this, arguments) || this;
  75687. }
  75688. /**
  75689. * Gets a string describing the action executed by the current optimization
  75690. */
  75691. CustomOptimization.prototype.getDescription = function () {
  75692. if (this.onGetDescription) {
  75693. return this.onGetDescription();
  75694. }
  75695. return "Running user defined callback";
  75696. };
  75697. /**
  75698. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75699. * @param scene defines the current scene where to apply this optimization
  75700. */
  75701. CustomOptimization.prototype.apply = function (scene) {
  75702. if (this.onApply) {
  75703. return this.onApply(scene);
  75704. }
  75705. return true;
  75706. };
  75707. ;
  75708. return CustomOptimization;
  75709. }(SceneOptimization));
  75710. BABYLON.CustomOptimization = CustomOptimization;
  75711. /**
  75712. * Defines an optimization used to turn particles off
  75713. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75714. */
  75715. var ParticlesOptimization = /** @class */ (function (_super) {
  75716. __extends(ParticlesOptimization, _super);
  75717. function ParticlesOptimization() {
  75718. return _super !== null && _super.apply(this, arguments) || this;
  75719. }
  75720. /**
  75721. * Gets a string describing the action executed by the current optimization
  75722. */
  75723. ParticlesOptimization.prototype.getDescription = function () {
  75724. return "Turning particles off";
  75725. };
  75726. /**
  75727. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75728. * @param scene defines the current scene where to apply this optimization
  75729. */
  75730. ParticlesOptimization.prototype.apply = function (scene) {
  75731. scene.particlesEnabled = false;
  75732. return true;
  75733. };
  75734. ;
  75735. return ParticlesOptimization;
  75736. }(SceneOptimization));
  75737. BABYLON.ParticlesOptimization = ParticlesOptimization;
  75738. /**
  75739. * Defines an optimization used to turn render targets off
  75740. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75741. */
  75742. var RenderTargetsOptimization = /** @class */ (function (_super) {
  75743. __extends(RenderTargetsOptimization, _super);
  75744. function RenderTargetsOptimization() {
  75745. return _super !== null && _super.apply(this, arguments) || this;
  75746. }
  75747. /**
  75748. * Gets a string describing the action executed by the current optimization
  75749. */
  75750. RenderTargetsOptimization.prototype.getDescription = function () {
  75751. return "Turning render targets off";
  75752. };
  75753. /**
  75754. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75755. * @param scene defines the current scene where to apply this optimization
  75756. */
  75757. RenderTargetsOptimization.prototype.apply = function (scene) {
  75758. scene.renderTargetsEnabled = false;
  75759. return true;
  75760. };
  75761. ;
  75762. return RenderTargetsOptimization;
  75763. }(SceneOptimization));
  75764. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  75765. /**
  75766. * Defines an optimization used to merge meshes with compatible materials
  75767. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75768. */
  75769. var MergeMeshesOptimization = /** @class */ (function (_super) {
  75770. __extends(MergeMeshesOptimization, _super);
  75771. function MergeMeshesOptimization() {
  75772. var _this = _super !== null && _super.apply(this, arguments) || this;
  75773. _this._canBeMerged = function (abstractMesh) {
  75774. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  75775. return false;
  75776. }
  75777. var mesh = abstractMesh;
  75778. if (!mesh.isVisible || !mesh.isEnabled()) {
  75779. return false;
  75780. }
  75781. if (mesh.instances.length > 0) {
  75782. return false;
  75783. }
  75784. if (mesh.skeleton || mesh.hasLODLevels) {
  75785. return false;
  75786. }
  75787. if (mesh.parent) {
  75788. return false;
  75789. }
  75790. return true;
  75791. };
  75792. return _this;
  75793. }
  75794. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  75795. /**
  75796. * Gets or sets a boolean which defines if optimization octree has to be updated
  75797. */
  75798. get: function () {
  75799. return MergeMeshesOptimization._UpdateSelectionTree;
  75800. },
  75801. /**
  75802. * Gets or sets a boolean which defines if optimization octree has to be updated
  75803. */
  75804. set: function (value) {
  75805. MergeMeshesOptimization._UpdateSelectionTree = value;
  75806. },
  75807. enumerable: true,
  75808. configurable: true
  75809. });
  75810. /**
  75811. * Gets a string describing the action executed by the current optimization
  75812. */
  75813. MergeMeshesOptimization.prototype.getDescription = function () {
  75814. return "Merging similar meshes together";
  75815. };
  75816. /**
  75817. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75818. * @param scene defines the current scene where to apply this optimization
  75819. */
  75820. MergeMeshesOptimization.prototype.apply = function (scene, updateSelectionTree) {
  75821. var globalPool = scene.meshes.slice(0);
  75822. var globalLength = globalPool.length;
  75823. for (var index = 0; index < globalLength; index++) {
  75824. var currentPool = new Array();
  75825. var current = globalPool[index];
  75826. // Checks
  75827. if (!this._canBeMerged(current)) {
  75828. continue;
  75829. }
  75830. currentPool.push(current);
  75831. // Find compatible meshes
  75832. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  75833. var otherMesh = globalPool[subIndex];
  75834. if (!this._canBeMerged(otherMesh)) {
  75835. continue;
  75836. }
  75837. if (otherMesh.material !== current.material) {
  75838. continue;
  75839. }
  75840. if (otherMesh.checkCollisions !== current.checkCollisions) {
  75841. continue;
  75842. }
  75843. currentPool.push(otherMesh);
  75844. globalLength--;
  75845. globalPool.splice(subIndex, 1);
  75846. subIndex--;
  75847. }
  75848. if (currentPool.length < 2) {
  75849. continue;
  75850. }
  75851. // Merge meshes
  75852. BABYLON.Mesh.MergeMeshes(currentPool);
  75853. }
  75854. if (updateSelectionTree != undefined) {
  75855. if (updateSelectionTree) {
  75856. scene.createOrUpdateSelectionOctree();
  75857. }
  75858. }
  75859. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  75860. scene.createOrUpdateSelectionOctree();
  75861. }
  75862. return true;
  75863. };
  75864. ;
  75865. MergeMeshesOptimization._UpdateSelectionTree = false;
  75866. return MergeMeshesOptimization;
  75867. }(SceneOptimization));
  75868. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  75869. /**
  75870. * Defines a list of options used by SceneOptimizer
  75871. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75872. */
  75873. var SceneOptimizerOptions = /** @class */ (function () {
  75874. /**
  75875. * Creates a new list of options used by SceneOptimizer
  75876. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  75877. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  75878. */
  75879. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  75880. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  75881. if (trackerDuration === void 0) { trackerDuration = 2000; }
  75882. this.targetFrameRate = targetFrameRate;
  75883. this.trackerDuration = trackerDuration;
  75884. /**
  75885. * Gets the list of optimizations to apply
  75886. */
  75887. this.optimizations = new Array();
  75888. }
  75889. /**
  75890. * Add a new optimization
  75891. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  75892. */
  75893. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  75894. this.optimizations.push(optimization);
  75895. return this;
  75896. };
  75897. /**
  75898. * Add a new custom optimization
  75899. * @param onApply defines the callback called to apply the custom optimization.
  75900. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  75901. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75902. */
  75903. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  75904. if (priority === void 0) { priority = 0; }
  75905. var optimization = new CustomOptimization(priority);
  75906. optimization.onApply = onApply;
  75907. optimization.onGetDescription = onGetDescription;
  75908. this.optimizations.push(optimization);
  75909. return this;
  75910. };
  75911. /**
  75912. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  75913. * @param targetFrameRate defines the target frame rate (60 by default)
  75914. * @returns a SceneOptimizerOptions object
  75915. */
  75916. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  75917. var result = new SceneOptimizerOptions(targetFrameRate);
  75918. var priority = 0;
  75919. result.addOptimization(new MergeMeshesOptimization(priority));
  75920. result.addOptimization(new ShadowsOptimization(priority));
  75921. result.addOptimization(new LensFlaresOptimization(priority));
  75922. // Next priority
  75923. priority++;
  75924. result.addOptimization(new PostProcessesOptimization(priority));
  75925. result.addOptimization(new ParticlesOptimization(priority));
  75926. // Next priority
  75927. priority++;
  75928. result.addOptimization(new TextureOptimization(priority, 1024));
  75929. return result;
  75930. };
  75931. /**
  75932. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  75933. * @param targetFrameRate defines the target frame rate (60 by default)
  75934. * @returns a SceneOptimizerOptions object
  75935. */
  75936. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  75937. var result = new SceneOptimizerOptions(targetFrameRate);
  75938. var priority = 0;
  75939. result.addOptimization(new MergeMeshesOptimization(priority));
  75940. result.addOptimization(new ShadowsOptimization(priority));
  75941. result.addOptimization(new LensFlaresOptimization(priority));
  75942. // Next priority
  75943. priority++;
  75944. result.addOptimization(new PostProcessesOptimization(priority));
  75945. result.addOptimization(new ParticlesOptimization(priority));
  75946. // Next priority
  75947. priority++;
  75948. result.addOptimization(new TextureOptimization(priority, 512));
  75949. // Next priority
  75950. priority++;
  75951. result.addOptimization(new RenderTargetsOptimization(priority));
  75952. // Next priority
  75953. priority++;
  75954. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  75955. return result;
  75956. };
  75957. /**
  75958. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  75959. * @param targetFrameRate defines the target frame rate (60 by default)
  75960. * @returns a SceneOptimizerOptions object
  75961. */
  75962. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  75963. var result = new SceneOptimizerOptions(targetFrameRate);
  75964. var priority = 0;
  75965. result.addOptimization(new MergeMeshesOptimization(priority));
  75966. result.addOptimization(new ShadowsOptimization(priority));
  75967. result.addOptimization(new LensFlaresOptimization(priority));
  75968. // Next priority
  75969. priority++;
  75970. result.addOptimization(new PostProcessesOptimization(priority));
  75971. result.addOptimization(new ParticlesOptimization(priority));
  75972. // Next priority
  75973. priority++;
  75974. result.addOptimization(new TextureOptimization(priority, 256));
  75975. // Next priority
  75976. priority++;
  75977. result.addOptimization(new RenderTargetsOptimization(priority));
  75978. // Next priority
  75979. priority++;
  75980. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  75981. return result;
  75982. };
  75983. return SceneOptimizerOptions;
  75984. }());
  75985. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  75986. /**
  75987. * Class used to run optimizations in order to reach a target frame rate
  75988. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75989. */
  75990. var SceneOptimizer = /** @class */ (function () {
  75991. /**
  75992. * Creates a new SceneOptimizer
  75993. * @param scene defines the scene to work on
  75994. * @param options defines the options to use with the SceneOptimizer
  75995. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  75996. */
  75997. function SceneOptimizer(scene, options, autoGeneratePriorities) {
  75998. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  75999. var _this = this;
  76000. this._isRunning = false;
  76001. this._currentPriorityLevel = 0;
  76002. this._targetFrameRate = 60;
  76003. this._trackerDuration = 2000;
  76004. this._currentFrameRate = 0;
  76005. /**
  76006. * Defines an observable called when the optimizer reaches the target frame rate
  76007. */
  76008. this.onSuccessObservable = new BABYLON.Observable();
  76009. /**
  76010. * Defines an observable called when the optimizer enables an optimization
  76011. */
  76012. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  76013. /**
  76014. * Defines an observable called when the optimizer is not able to reach the target frame rate
  76015. */
  76016. this.onFailureObservable = new BABYLON.Observable();
  76017. if (!options) {
  76018. this._options = new SceneOptimizerOptions();
  76019. }
  76020. else {
  76021. this._options = options;
  76022. }
  76023. if (this._options.targetFrameRate) {
  76024. this._targetFrameRate = this._options.targetFrameRate;
  76025. }
  76026. if (this._options.trackerDuration) {
  76027. this._trackerDuration = this._options.trackerDuration;
  76028. }
  76029. if (autoGeneratePriorities) {
  76030. var priority = 0;
  76031. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  76032. var optim = _a[_i];
  76033. optim.priority = priority++;
  76034. }
  76035. }
  76036. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76037. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  76038. _this._sceneDisposeObserver = null;
  76039. _this.dispose();
  76040. });
  76041. }
  76042. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  76043. /**
  76044. * Gets the current priority level (0 at start)
  76045. */
  76046. get: function () {
  76047. return this._currentPriorityLevel;
  76048. },
  76049. enumerable: true,
  76050. configurable: true
  76051. });
  76052. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  76053. /**
  76054. * Gets the current frame rate checked by the SceneOptimizer
  76055. */
  76056. get: function () {
  76057. return this._currentFrameRate;
  76058. },
  76059. enumerable: true,
  76060. configurable: true
  76061. });
  76062. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  76063. /**
  76064. * Gets or sets the current target frame rate (60 by default)
  76065. */
  76066. get: function () {
  76067. return this._targetFrameRate;
  76068. },
  76069. /**
  76070. * Gets or sets the current target frame rate (60 by default)
  76071. */
  76072. set: function (value) {
  76073. this._targetFrameRate = value;
  76074. },
  76075. enumerable: true,
  76076. configurable: true
  76077. });
  76078. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  76079. /**
  76080. * Gets or sets the current interval between two checks (every 2000ms by default)
  76081. */
  76082. get: function () {
  76083. return this._trackerDuration;
  76084. },
  76085. /**
  76086. * Gets or sets the current interval between two checks (every 2000ms by default)
  76087. */
  76088. set: function (value) {
  76089. this._trackerDuration = value;
  76090. },
  76091. enumerable: true,
  76092. configurable: true
  76093. });
  76094. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  76095. /**
  76096. * Gets the list of active optimizations
  76097. */
  76098. get: function () {
  76099. return this._options.optimizations;
  76100. },
  76101. enumerable: true,
  76102. configurable: true
  76103. });
  76104. /**
  76105. * Stops the current optimizer
  76106. */
  76107. SceneOptimizer.prototype.stop = function () {
  76108. this._isRunning = false;
  76109. };
  76110. SceneOptimizer.prototype.reset = function () {
  76111. this._currentPriorityLevel = 0;
  76112. };
  76113. SceneOptimizer.prototype.start = function () {
  76114. var _this = this;
  76115. if (this._isRunning) {
  76116. return;
  76117. }
  76118. this._isRunning = true;
  76119. // Let's wait for the scene to be ready before running our check
  76120. this._scene.executeWhenReady(function () {
  76121. setTimeout(function () {
  76122. _this._checkCurrentState();
  76123. }, _this._trackerDuration);
  76124. });
  76125. };
  76126. SceneOptimizer.prototype._checkCurrentState = function () {
  76127. var _this = this;
  76128. if (!this._isRunning) {
  76129. return;
  76130. }
  76131. var scene = this._scene;
  76132. var options = this._options;
  76133. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  76134. if (this._currentFrameRate >= this._targetFrameRate) {
  76135. this._isRunning = false;
  76136. this.onSuccessObservable.notifyObservers(this);
  76137. return;
  76138. }
  76139. // Apply current level of optimizations
  76140. var allDone = true;
  76141. var noOptimizationApplied = true;
  76142. for (var index = 0; index < options.optimizations.length; index++) {
  76143. var optimization = options.optimizations[index];
  76144. if (optimization.priority === this._currentPriorityLevel) {
  76145. noOptimizationApplied = false;
  76146. allDone = allDone && optimization.apply(scene);
  76147. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  76148. }
  76149. }
  76150. // If no optimization was applied, this is a failure :(
  76151. if (noOptimizationApplied) {
  76152. this._isRunning = false;
  76153. this.onFailureObservable.notifyObservers(this);
  76154. return;
  76155. }
  76156. // If all optimizations were done, move to next level
  76157. if (allDone) {
  76158. this._currentPriorityLevel++;
  76159. }
  76160. // Let's the system running for a specific amount of time before checking FPS
  76161. scene.executeWhenReady(function () {
  76162. setTimeout(function () {
  76163. _this._checkCurrentState();
  76164. }, _this._trackerDuration);
  76165. });
  76166. };
  76167. /**
  76168. * Release all resources
  76169. */
  76170. SceneOptimizer.prototype.dispose = function () {
  76171. this.stop();
  76172. this.onSuccessObservable.clear();
  76173. this.onFailureObservable.clear();
  76174. this.onNewOptimizationAppliedObservable.clear();
  76175. if (this._sceneDisposeObserver) {
  76176. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  76177. }
  76178. };
  76179. /**
  76180. * Helper function to create a SceneOptimizer with one single line of code
  76181. * @param scene defines the scene to work on
  76182. * @param options defines the options to use with the SceneOptimizer
  76183. * @param onSuccess defines a callback to call on success
  76184. * @param onFailure defines a callback to call on failure
  76185. */
  76186. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  76187. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  76188. if (onSuccess) {
  76189. optimizer.onSuccessObservable.add(function () {
  76190. onSuccess();
  76191. });
  76192. }
  76193. if (onFailure) {
  76194. optimizer.onFailureObservable.add(function () {
  76195. onFailure();
  76196. });
  76197. }
  76198. optimizer.start();
  76199. return optimizer;
  76200. };
  76201. return SceneOptimizer;
  76202. }());
  76203. BABYLON.SceneOptimizer = SceneOptimizer;
  76204. })(BABYLON || (BABYLON = {}));
  76205. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  76206. var BABYLON;
  76207. (function (BABYLON) {
  76208. var OutlineRenderer = /** @class */ (function () {
  76209. function OutlineRenderer(scene) {
  76210. this.zOffset = 1;
  76211. this._scene = scene;
  76212. }
  76213. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  76214. var _this = this;
  76215. if (useOverlay === void 0) { useOverlay = false; }
  76216. var scene = this._scene;
  76217. var engine = this._scene.getEngine();
  76218. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76219. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  76220. return;
  76221. }
  76222. var mesh = subMesh.getRenderingMesh();
  76223. var material = subMesh.getMaterial();
  76224. if (!material || !scene.activeCamera) {
  76225. return;
  76226. }
  76227. engine.enableEffect(this._effect);
  76228. // Logarithmic depth
  76229. if (material.useLogarithmicDepth) {
  76230. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  76231. }
  76232. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  76233. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  76234. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76235. // Bones
  76236. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76237. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76238. }
  76239. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  76240. // Alpha test
  76241. if (material && material.needAlphaTesting()) {
  76242. var alphaTexture = material.getAlphaTestTexture();
  76243. if (alphaTexture) {
  76244. this._effect.setTexture("diffuseSampler", alphaTexture);
  76245. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76246. }
  76247. }
  76248. engine.setZOffset(-this.zOffset);
  76249. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  76250. engine.setZOffset(0);
  76251. };
  76252. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  76253. var defines = [];
  76254. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76255. var mesh = subMesh.getMesh();
  76256. var material = subMesh.getMaterial();
  76257. if (material) {
  76258. // Alpha test
  76259. if (material.needAlphaTesting()) {
  76260. defines.push("#define ALPHATEST");
  76261. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76262. attribs.push(BABYLON.VertexBuffer.UVKind);
  76263. defines.push("#define UV1");
  76264. }
  76265. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76266. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76267. defines.push("#define UV2");
  76268. }
  76269. }
  76270. //Logarithmic depth
  76271. if (material.useLogarithmicDepth) {
  76272. defines.push("#define LOGARITHMICDEPTH");
  76273. }
  76274. }
  76275. // Bones
  76276. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76277. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76278. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76279. if (mesh.numBoneInfluencers > 4) {
  76280. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76281. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76282. }
  76283. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76284. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76285. }
  76286. else {
  76287. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76288. }
  76289. // Instances
  76290. if (useInstances) {
  76291. defines.push("#define INSTANCES");
  76292. attribs.push("world0");
  76293. attribs.push("world1");
  76294. attribs.push("world2");
  76295. attribs.push("world3");
  76296. }
  76297. // Get correct effect
  76298. var join = defines.join("\n");
  76299. if (this._cachedDefines !== join) {
  76300. this._cachedDefines = join;
  76301. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  76302. }
  76303. return this._effect.isReady();
  76304. };
  76305. return OutlineRenderer;
  76306. }());
  76307. BABYLON.OutlineRenderer = OutlineRenderer;
  76308. })(BABYLON || (BABYLON = {}));
  76309. //# sourceMappingURL=babylon.outlineRenderer.js.map
  76310. var BABYLON;
  76311. (function (BABYLON) {
  76312. var FaceAdjacencies = /** @class */ (function () {
  76313. function FaceAdjacencies() {
  76314. this.edges = new Array();
  76315. this.edgesConnectedCount = 0;
  76316. }
  76317. return FaceAdjacencies;
  76318. }());
  76319. var EdgesRenderer = /** @class */ (function () {
  76320. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  76321. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  76322. if (epsilon === void 0) { epsilon = 0.95; }
  76323. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  76324. this.edgesWidthScalerForOrthographic = 1000.0;
  76325. this.edgesWidthScalerForPerspective = 50.0;
  76326. this._linesPositions = new Array();
  76327. this._linesNormals = new Array();
  76328. this._linesIndices = new Array();
  76329. this._buffers = {};
  76330. this._checkVerticesInsteadOfIndices = false;
  76331. this._source = source;
  76332. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  76333. this._epsilon = epsilon;
  76334. this._prepareRessources();
  76335. this._generateEdgesLines();
  76336. }
  76337. EdgesRenderer.prototype._prepareRessources = function () {
  76338. if (this._lineShader) {
  76339. return;
  76340. }
  76341. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  76342. attributes: ["position", "normal"],
  76343. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  76344. });
  76345. this._lineShader.disableDepthWrite = true;
  76346. this._lineShader.backFaceCulling = false;
  76347. };
  76348. EdgesRenderer.prototype._rebuild = function () {
  76349. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  76350. if (buffer) {
  76351. buffer._rebuild();
  76352. }
  76353. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  76354. if (buffer) {
  76355. buffer._rebuild();
  76356. }
  76357. var scene = this._source.getScene();
  76358. var engine = scene.getEngine();
  76359. this._ib = engine.createIndexBuffer(this._linesIndices);
  76360. };
  76361. EdgesRenderer.prototype.dispose = function () {
  76362. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  76363. if (buffer) {
  76364. buffer.dispose();
  76365. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  76366. }
  76367. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  76368. if (buffer) {
  76369. buffer.dispose();
  76370. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  76371. }
  76372. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  76373. this._lineShader.dispose();
  76374. };
  76375. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  76376. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  76377. return 0;
  76378. }
  76379. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  76380. return 1;
  76381. }
  76382. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  76383. return 2;
  76384. }
  76385. return -1;
  76386. };
  76387. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  76388. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  76389. return 0;
  76390. }
  76391. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  76392. return 1;
  76393. }
  76394. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  76395. return 2;
  76396. }
  76397. return -1;
  76398. };
  76399. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  76400. var needToCreateLine;
  76401. if (edge === undefined) {
  76402. needToCreateLine = true;
  76403. }
  76404. else {
  76405. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  76406. needToCreateLine = dotProduct < this._epsilon;
  76407. }
  76408. if (needToCreateLine) {
  76409. var offset = this._linesPositions.length / 3;
  76410. var normal = p0.subtract(p1);
  76411. normal.normalize();
  76412. // Positions
  76413. this._linesPositions.push(p0.x);
  76414. this._linesPositions.push(p0.y);
  76415. this._linesPositions.push(p0.z);
  76416. this._linesPositions.push(p0.x);
  76417. this._linesPositions.push(p0.y);
  76418. this._linesPositions.push(p0.z);
  76419. this._linesPositions.push(p1.x);
  76420. this._linesPositions.push(p1.y);
  76421. this._linesPositions.push(p1.z);
  76422. this._linesPositions.push(p1.x);
  76423. this._linesPositions.push(p1.y);
  76424. this._linesPositions.push(p1.z);
  76425. // Normals
  76426. this._linesNormals.push(p1.x);
  76427. this._linesNormals.push(p1.y);
  76428. this._linesNormals.push(p1.z);
  76429. this._linesNormals.push(-1);
  76430. this._linesNormals.push(p1.x);
  76431. this._linesNormals.push(p1.y);
  76432. this._linesNormals.push(p1.z);
  76433. this._linesNormals.push(1);
  76434. this._linesNormals.push(p0.x);
  76435. this._linesNormals.push(p0.y);
  76436. this._linesNormals.push(p0.z);
  76437. this._linesNormals.push(-1);
  76438. this._linesNormals.push(p0.x);
  76439. this._linesNormals.push(p0.y);
  76440. this._linesNormals.push(p0.z);
  76441. this._linesNormals.push(1);
  76442. // Indices
  76443. this._linesIndices.push(offset);
  76444. this._linesIndices.push(offset + 1);
  76445. this._linesIndices.push(offset + 2);
  76446. this._linesIndices.push(offset);
  76447. this._linesIndices.push(offset + 2);
  76448. this._linesIndices.push(offset + 3);
  76449. }
  76450. };
  76451. EdgesRenderer.prototype._generateEdgesLines = function () {
  76452. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  76453. var indices = this._source.getIndices();
  76454. if (!indices || !positions) {
  76455. return;
  76456. }
  76457. // First let's find adjacencies
  76458. var adjacencies = new Array();
  76459. var faceNormals = new Array();
  76460. var index;
  76461. var faceAdjacencies;
  76462. // Prepare faces
  76463. for (index = 0; index < indices.length; index += 3) {
  76464. faceAdjacencies = new FaceAdjacencies();
  76465. var p0Index = indices[index];
  76466. var p1Index = indices[index + 1];
  76467. var p2Index = indices[index + 2];
  76468. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  76469. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  76470. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  76471. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  76472. faceNormal.normalize();
  76473. faceNormals.push(faceNormal);
  76474. adjacencies.push(faceAdjacencies);
  76475. }
  76476. // Scan
  76477. for (index = 0; index < adjacencies.length; index++) {
  76478. faceAdjacencies = adjacencies[index];
  76479. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  76480. var otherFaceAdjacencies = adjacencies[otherIndex];
  76481. if (faceAdjacencies.edgesConnectedCount === 3) {
  76482. break;
  76483. }
  76484. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  76485. continue;
  76486. }
  76487. var otherP0 = indices[otherIndex * 3];
  76488. var otherP1 = indices[otherIndex * 3 + 1];
  76489. var otherP2 = indices[otherIndex * 3 + 2];
  76490. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  76491. var otherEdgeIndex = 0;
  76492. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  76493. continue;
  76494. }
  76495. switch (edgeIndex) {
  76496. case 0:
  76497. if (this._checkVerticesInsteadOfIndices) {
  76498. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76499. }
  76500. else {
  76501. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  76502. }
  76503. break;
  76504. case 1:
  76505. if (this._checkVerticesInsteadOfIndices) {
  76506. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76507. }
  76508. else {
  76509. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  76510. }
  76511. break;
  76512. case 2:
  76513. if (this._checkVerticesInsteadOfIndices) {
  76514. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76515. }
  76516. else {
  76517. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  76518. }
  76519. break;
  76520. }
  76521. if (otherEdgeIndex === -1) {
  76522. continue;
  76523. }
  76524. faceAdjacencies.edges[edgeIndex] = otherIndex;
  76525. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  76526. faceAdjacencies.edgesConnectedCount++;
  76527. otherFaceAdjacencies.edgesConnectedCount++;
  76528. if (faceAdjacencies.edgesConnectedCount === 3) {
  76529. break;
  76530. }
  76531. }
  76532. }
  76533. }
  76534. // Create lines
  76535. for (index = 0; index < adjacencies.length; index++) {
  76536. // 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
  76537. var current = adjacencies[index];
  76538. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  76539. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  76540. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  76541. }
  76542. // Merge into a single mesh
  76543. var engine = this._source.getScene().getEngine();
  76544. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  76545. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  76546. this._ib = engine.createIndexBuffer(this._linesIndices);
  76547. this._indicesCount = this._linesIndices.length;
  76548. };
  76549. EdgesRenderer.prototype.render = function () {
  76550. var scene = this._source.getScene();
  76551. if (!this._lineShader.isReady() || !scene.activeCamera) {
  76552. return;
  76553. }
  76554. var engine = scene.getEngine();
  76555. this._lineShader._preBind();
  76556. // VBOs
  76557. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  76558. scene.resetCachedMaterial();
  76559. this._lineShader.setColor4("color", this._source.edgesColor);
  76560. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  76561. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  76562. }
  76563. else {
  76564. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  76565. }
  76566. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  76567. this._lineShader.bind(this._source.getWorldMatrix());
  76568. // Draw order
  76569. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  76570. this._lineShader.unbind();
  76571. engine.setDepthWrite(true);
  76572. };
  76573. return EdgesRenderer;
  76574. }());
  76575. BABYLON.EdgesRenderer = EdgesRenderer;
  76576. })(BABYLON || (BABYLON = {}));
  76577. //# sourceMappingURL=babylon.edgesRenderer.js.map
  76578. var BABYLON;
  76579. (function (BABYLON) {
  76580. /**
  76581. * Special Glow Blur post process only blurring the alpha channel
  76582. * It enforces keeping the most luminous color in the color channel.
  76583. */
  76584. var GlowBlurPostProcess = /** @class */ (function (_super) {
  76585. __extends(GlowBlurPostProcess, _super);
  76586. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  76587. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76588. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  76589. _this.direction = direction;
  76590. _this.kernel = kernel;
  76591. _this.onApplyObservable.add(function (effect) {
  76592. effect.setFloat2("screenSize", _this.width, _this.height);
  76593. effect.setVector2("direction", _this.direction);
  76594. effect.setFloat("blurWidth", _this.kernel);
  76595. });
  76596. return _this;
  76597. }
  76598. return GlowBlurPostProcess;
  76599. }(BABYLON.PostProcess));
  76600. /**
  76601. * The highlight layer Helps adding a glow effect around a mesh.
  76602. *
  76603. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  76604. * glowy meshes to your scene.
  76605. *
  76606. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  76607. */
  76608. var HighlightLayer = /** @class */ (function () {
  76609. /**
  76610. * Instantiates a new highlight Layer and references it to the scene..
  76611. * @param name The name of the layer
  76612. * @param scene The scene to use the layer in
  76613. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  76614. */
  76615. function HighlightLayer(name, scene, options) {
  76616. this.name = name;
  76617. this._vertexBuffers = {};
  76618. this._mainTextureDesiredSize = { width: 0, height: 0 };
  76619. this._meshes = {};
  76620. this._maxSize = 0;
  76621. this._shouldRender = false;
  76622. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  76623. this._excludedMeshes = {};
  76624. /**
  76625. * Specifies whether or not the inner glow is ACTIVE in the layer.
  76626. */
  76627. this.innerGlow = true;
  76628. /**
  76629. * Specifies whether or not the outer glow is ACTIVE in the layer.
  76630. */
  76631. this.outerGlow = true;
  76632. /**
  76633. * Specifies wether the highlight layer is enabled or not.
  76634. */
  76635. this.isEnabled = true;
  76636. /**
  76637. * An event triggered when the highlight layer has been disposed.
  76638. * @type {BABYLON.Observable}
  76639. */
  76640. this.onDisposeObservable = new BABYLON.Observable();
  76641. /**
  76642. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  76643. * @type {BABYLON.Observable}
  76644. */
  76645. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  76646. /**
  76647. * An event triggered when the highlight layer is being blurred.
  76648. * @type {BABYLON.Observable}
  76649. */
  76650. this.onBeforeBlurObservable = new BABYLON.Observable();
  76651. /**
  76652. * An event triggered when the highlight layer has been blurred.
  76653. * @type {BABYLON.Observable}
  76654. */
  76655. this.onAfterBlurObservable = new BABYLON.Observable();
  76656. /**
  76657. * An event triggered when the glowing blurred texture is being merged in the scene.
  76658. * @type {BABYLON.Observable}
  76659. */
  76660. this.onBeforeComposeObservable = new BABYLON.Observable();
  76661. /**
  76662. * An event triggered when the glowing blurred texture has been merged in the scene.
  76663. * @type {BABYLON.Observable}
  76664. */
  76665. this.onAfterComposeObservable = new BABYLON.Observable();
  76666. /**
  76667. * An event triggered when the highlight layer changes its size.
  76668. * @type {BABYLON.Observable}
  76669. */
  76670. this.onSizeChangedObservable = new BABYLON.Observable();
  76671. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76672. var engine = scene.getEngine();
  76673. this._engine = engine;
  76674. this._maxSize = this._engine.getCaps().maxTextureSize;
  76675. this._scene.highlightLayers.push(this);
  76676. // Warn on stencil.
  76677. if (!this._engine.isStencilEnable) {
  76678. 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 }");
  76679. }
  76680. // Adapt options
  76681. this._options = options || {
  76682. mainTextureRatio: 0.5,
  76683. blurTextureSizeRatio: 0.5,
  76684. blurHorizontalSize: 1.0,
  76685. blurVerticalSize: 1.0,
  76686. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  76687. camera: null
  76688. };
  76689. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  76690. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  76691. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  76692. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  76693. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  76694. // VBO
  76695. var vertices = [];
  76696. vertices.push(1, 1);
  76697. vertices.push(-1, 1);
  76698. vertices.push(-1, -1);
  76699. vertices.push(1, -1);
  76700. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76701. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  76702. this._createIndexBuffer();
  76703. // Effect
  76704. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  76705. // Render target
  76706. this.setMainTextureSize();
  76707. // Create Textures and post processes
  76708. this.createTextureAndPostProcesses();
  76709. }
  76710. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  76711. /**
  76712. * Gets the horizontal size of the blur.
  76713. */
  76714. get: function () {
  76715. return this._horizontalBlurPostprocess.kernel;
  76716. },
  76717. /**
  76718. * Specifies the horizontal size of the blur.
  76719. */
  76720. set: function (value) {
  76721. this._horizontalBlurPostprocess.kernel = value;
  76722. },
  76723. enumerable: true,
  76724. configurable: true
  76725. });
  76726. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  76727. /**
  76728. * Gets the vertical size of the blur.
  76729. */
  76730. get: function () {
  76731. return this._verticalBlurPostprocess.kernel;
  76732. },
  76733. /**
  76734. * Specifies the vertical size of the blur.
  76735. */
  76736. set: function (value) {
  76737. this._verticalBlurPostprocess.kernel = value;
  76738. },
  76739. enumerable: true,
  76740. configurable: true
  76741. });
  76742. Object.defineProperty(HighlightLayer.prototype, "camera", {
  76743. /**
  76744. * Gets the camera attached to the layer.
  76745. */
  76746. get: function () {
  76747. return this._options.camera;
  76748. },
  76749. enumerable: true,
  76750. configurable: true
  76751. });
  76752. HighlightLayer.prototype._createIndexBuffer = function () {
  76753. var engine = this._scene.getEngine();
  76754. // Indices
  76755. var indices = [];
  76756. indices.push(0);
  76757. indices.push(1);
  76758. indices.push(2);
  76759. indices.push(0);
  76760. indices.push(2);
  76761. indices.push(3);
  76762. this._indexBuffer = engine.createIndexBuffer(indices);
  76763. };
  76764. HighlightLayer.prototype._rebuild = function () {
  76765. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76766. if (vb) {
  76767. vb._rebuild();
  76768. }
  76769. this._createIndexBuffer();
  76770. };
  76771. /**
  76772. * Creates the render target textures and post processes used in the highlight layer.
  76773. */
  76774. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  76775. var _this = this;
  76776. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  76777. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  76778. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  76779. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  76780. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  76781. width: this._mainTextureDesiredSize.width,
  76782. height: this._mainTextureDesiredSize.height
  76783. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76784. this._mainTexture.activeCamera = this._options.camera;
  76785. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76786. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76787. this._mainTexture.anisotropicFilteringLevel = 1;
  76788. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76789. this._mainTexture.renderParticles = false;
  76790. this._mainTexture.renderList = null;
  76791. this._mainTexture.ignoreCameraViewport = true;
  76792. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  76793. width: blurTextureWidth,
  76794. height: blurTextureHeight
  76795. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76796. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76797. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76798. this._blurTexture.anisotropicFilteringLevel = 16;
  76799. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76800. this._blurTexture.renderParticles = false;
  76801. this._blurTexture.ignoreCameraViewport = true;
  76802. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76803. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  76804. effect.setTexture("textureSampler", _this._mainTexture);
  76805. });
  76806. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  76807. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76808. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  76809. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76810. });
  76811. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76812. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  76813. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76814. });
  76815. }
  76816. else {
  76817. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76818. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  76819. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76820. });
  76821. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76822. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  76823. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76824. });
  76825. }
  76826. this._mainTexture.onAfterUnbindObservable.add(function () {
  76827. _this.onBeforeBlurObservable.notifyObservers(_this);
  76828. var internalTexture = _this._blurTexture.getInternalTexture();
  76829. if (internalTexture) {
  76830. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  76831. }
  76832. _this.onAfterBlurObservable.notifyObservers(_this);
  76833. });
  76834. // Custom render function
  76835. var renderSubMesh = function (subMesh) {
  76836. if (!_this._meshes) {
  76837. return;
  76838. }
  76839. var material = subMesh.getMaterial();
  76840. var mesh = subMesh.getRenderingMesh();
  76841. var scene = _this._scene;
  76842. var engine = scene.getEngine();
  76843. if (!material) {
  76844. return;
  76845. }
  76846. // Do not block in blend mode.
  76847. if (material.needAlphaBlendingForMesh(mesh)) {
  76848. return;
  76849. }
  76850. // Culling
  76851. engine.setState(material.backFaceCulling);
  76852. // Managing instances
  76853. var batch = mesh._getInstancesRenderList(subMesh._id);
  76854. if (batch.mustReturn) {
  76855. return;
  76856. }
  76857. // Excluded Mesh
  76858. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  76859. return;
  76860. }
  76861. ;
  76862. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76863. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  76864. var emissiveTexture = null;
  76865. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  76866. emissiveTexture = material.emissiveTexture;
  76867. }
  76868. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  76869. engine.enableEffect(_this._glowMapGenerationEffect);
  76870. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  76871. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  76872. if (highlightLayerMesh) {
  76873. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  76874. }
  76875. else {
  76876. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  76877. }
  76878. // Alpha test
  76879. if (material && material.needAlphaTesting()) {
  76880. var alphaTexture = material.getAlphaTestTexture();
  76881. if (alphaTexture) {
  76882. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  76883. var textureMatrix = alphaTexture.getTextureMatrix();
  76884. if (textureMatrix) {
  76885. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  76886. }
  76887. }
  76888. }
  76889. // Glow emissive only
  76890. if (emissiveTexture) {
  76891. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  76892. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  76893. }
  76894. // Bones
  76895. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76896. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76897. }
  76898. // Draw
  76899. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  76900. }
  76901. else {
  76902. // Need to reset refresh rate of the shadowMap
  76903. _this._mainTexture.resetRefreshCounter();
  76904. }
  76905. };
  76906. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76907. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  76908. var index;
  76909. var engine = _this._scene.getEngine();
  76910. if (depthOnlySubMeshes.length) {
  76911. engine.setColorWrite(false);
  76912. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76913. renderSubMesh(depthOnlySubMeshes.data[index]);
  76914. }
  76915. engine.setColorWrite(true);
  76916. }
  76917. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76918. renderSubMesh(opaqueSubMeshes.data[index]);
  76919. }
  76920. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76921. renderSubMesh(alphaTestSubMeshes.data[index]);
  76922. }
  76923. for (index = 0; index < transparentSubMeshes.length; index++) {
  76924. renderSubMesh(transparentSubMeshes.data[index]);
  76925. }
  76926. };
  76927. this._mainTexture.onClearObservable.add(function (engine) {
  76928. engine.clear(HighlightLayer.neutralColor, true, true, true);
  76929. });
  76930. };
  76931. /**
  76932. * Checks for the readiness of the element composing the layer.
  76933. * @param subMesh the mesh to check for
  76934. * @param useInstances specify wether or not to use instances to render the mesh
  76935. * @param emissiveTexture the associated emissive texture used to generate the glow
  76936. * @return true if ready otherwise, false
  76937. */
  76938. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  76939. var material = subMesh.getMaterial();
  76940. var mesh = subMesh.getRenderingMesh();
  76941. if (!material || !mesh || !this._meshes) {
  76942. return false;
  76943. }
  76944. var emissiveTexture = null;
  76945. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  76946. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  76947. emissiveTexture = material.emissiveTexture;
  76948. }
  76949. return this._isReady(subMesh, useInstances, emissiveTexture);
  76950. };
  76951. /**
  76952. * Checks for the readiness of the element composing the layer.
  76953. * @param subMesh the mesh to check for
  76954. * @param useInstances specify wether or not to use instances to render the mesh
  76955. * @param emissiveTexture the associated emissive texture used to generate the glow
  76956. * @return true if ready otherwise, false
  76957. */
  76958. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  76959. var material = subMesh.getMaterial();
  76960. if (!material) {
  76961. return false;
  76962. }
  76963. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  76964. return false;
  76965. }
  76966. var defines = [];
  76967. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76968. var mesh = subMesh.getMesh();
  76969. var uv1 = false;
  76970. var uv2 = false;
  76971. // Alpha test
  76972. if (material && material.needAlphaTesting()) {
  76973. var alphaTexture = material.getAlphaTestTexture();
  76974. if (alphaTexture) {
  76975. defines.push("#define ALPHATEST");
  76976. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  76977. alphaTexture.coordinatesIndex === 1) {
  76978. defines.push("#define DIFFUSEUV2");
  76979. uv2 = true;
  76980. }
  76981. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76982. defines.push("#define DIFFUSEUV1");
  76983. uv1 = true;
  76984. }
  76985. }
  76986. }
  76987. // Emissive
  76988. if (emissiveTexture) {
  76989. defines.push("#define EMISSIVE");
  76990. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  76991. emissiveTexture.coordinatesIndex === 1) {
  76992. defines.push("#define EMISSIVEUV2");
  76993. uv2 = true;
  76994. }
  76995. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76996. defines.push("#define EMISSIVEUV1");
  76997. uv1 = true;
  76998. }
  76999. }
  77000. if (uv1) {
  77001. attribs.push(BABYLON.VertexBuffer.UVKind);
  77002. defines.push("#define UV1");
  77003. }
  77004. if (uv2) {
  77005. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77006. defines.push("#define UV2");
  77007. }
  77008. // Bones
  77009. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77010. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77011. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77012. if (mesh.numBoneInfluencers > 4) {
  77013. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77014. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77015. }
  77016. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77017. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77018. }
  77019. else {
  77020. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77021. }
  77022. // Instances
  77023. if (useInstances) {
  77024. defines.push("#define INSTANCES");
  77025. attribs.push("world0");
  77026. attribs.push("world1");
  77027. attribs.push("world2");
  77028. attribs.push("world3");
  77029. }
  77030. // Get correct effect
  77031. var join = defines.join("\n");
  77032. if (this._cachedDefines !== join) {
  77033. this._cachedDefines = join;
  77034. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  77035. }
  77036. return this._glowMapGenerationEffect.isReady();
  77037. };
  77038. /**
  77039. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  77040. */
  77041. HighlightLayer.prototype.render = function () {
  77042. var currentEffect = this._glowMapMergeEffect;
  77043. // Check
  77044. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  77045. return;
  77046. var engine = this._scene.getEngine();
  77047. this.onBeforeComposeObservable.notifyObservers(this);
  77048. // Render
  77049. engine.enableEffect(currentEffect);
  77050. engine.setState(false);
  77051. // Cache
  77052. var previousStencilBuffer = engine.getStencilBuffer();
  77053. var previousStencilFunction = engine.getStencilFunction();
  77054. var previousStencilMask = engine.getStencilMask();
  77055. var previousStencilOperationPass = engine.getStencilOperationPass();
  77056. var previousStencilOperationFail = engine.getStencilOperationFail();
  77057. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  77058. var previousAlphaMode = engine.getAlphaMode();
  77059. // Texture
  77060. currentEffect.setTexture("textureSampler", this._blurTexture);
  77061. // VBOs
  77062. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  77063. // Stencil operations
  77064. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  77065. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  77066. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  77067. // Draw order
  77068. engine.setAlphaMode(this._options.alphaBlendingMode);
  77069. engine.setStencilMask(0x00);
  77070. engine.setStencilBuffer(true);
  77071. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  77072. if (this.outerGlow) {
  77073. currentEffect.setFloat("offset", 0);
  77074. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  77075. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77076. }
  77077. if (this.innerGlow) {
  77078. currentEffect.setFloat("offset", 1);
  77079. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  77080. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77081. }
  77082. // Restore Cache
  77083. engine.setStencilFunction(previousStencilFunction);
  77084. engine.setStencilMask(previousStencilMask);
  77085. engine.setAlphaMode(previousAlphaMode);
  77086. engine.setStencilBuffer(previousStencilBuffer);
  77087. engine.setStencilOperationPass(previousStencilOperationPass);
  77088. engine.setStencilOperationFail(previousStencilOperationFail);
  77089. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  77090. engine._stencilState.reset();
  77091. this.onAfterComposeObservable.notifyObservers(this);
  77092. // Handle size changes.
  77093. var size = this._mainTexture.getSize();
  77094. this.setMainTextureSize();
  77095. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  77096. // Recreate RTT and post processes on size change.
  77097. this.onSizeChangedObservable.notifyObservers(this);
  77098. this.disposeTextureAndPostProcesses();
  77099. this.createTextureAndPostProcesses();
  77100. }
  77101. };
  77102. /**
  77103. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  77104. * @param mesh The mesh to exclude from the highlight layer
  77105. */
  77106. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  77107. if (!this._excludedMeshes) {
  77108. return;
  77109. }
  77110. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  77111. if (!meshExcluded) {
  77112. this._excludedMeshes[mesh.uniqueId] = {
  77113. mesh: mesh,
  77114. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  77115. mesh.getEngine().setStencilBuffer(false);
  77116. }),
  77117. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  77118. mesh.getEngine().setStencilBuffer(true);
  77119. }),
  77120. };
  77121. }
  77122. };
  77123. /**
  77124. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  77125. * @param mesh The mesh to highlight
  77126. */
  77127. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  77128. if (!this._excludedMeshes) {
  77129. return;
  77130. }
  77131. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  77132. if (meshExcluded) {
  77133. if (meshExcluded.beforeRender) {
  77134. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  77135. }
  77136. if (meshExcluded.afterRender) {
  77137. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  77138. }
  77139. }
  77140. this._excludedMeshes[mesh.uniqueId] = null;
  77141. };
  77142. /**
  77143. * Determine if a given mesh will be highlighted by the current HighlightLayer
  77144. * @param mesh mesh to test
  77145. * @returns true if the mesh will be highlighted by the current HighlightLayer
  77146. */
  77147. HighlightLayer.prototype.hasMesh = function (mesh) {
  77148. if (!this._meshes) {
  77149. return false;
  77150. }
  77151. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  77152. };
  77153. /**
  77154. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  77155. * @param mesh The mesh to highlight
  77156. * @param color The color of the highlight
  77157. * @param glowEmissiveOnly Extract the glow from the emissive texture
  77158. */
  77159. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  77160. var _this = this;
  77161. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  77162. if (!this._meshes) {
  77163. return;
  77164. }
  77165. var meshHighlight = this._meshes[mesh.uniqueId];
  77166. if (meshHighlight) {
  77167. meshHighlight.color = color;
  77168. }
  77169. else {
  77170. this._meshes[mesh.uniqueId] = {
  77171. mesh: mesh,
  77172. color: color,
  77173. // Lambda required for capture due to Observable this context
  77174. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  77175. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  77176. _this.defaultStencilReference(mesh);
  77177. }
  77178. else {
  77179. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  77180. }
  77181. }),
  77182. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  77183. glowEmissiveOnly: glowEmissiveOnly
  77184. };
  77185. }
  77186. this._shouldRender = true;
  77187. };
  77188. /**
  77189. * Remove a mesh from the highlight layer in order to make it stop glowing.
  77190. * @param mesh The mesh to highlight
  77191. */
  77192. HighlightLayer.prototype.removeMesh = function (mesh) {
  77193. if (!this._meshes) {
  77194. return;
  77195. }
  77196. var meshHighlight = this._meshes[mesh.uniqueId];
  77197. if (meshHighlight) {
  77198. if (meshHighlight.observerHighlight) {
  77199. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  77200. }
  77201. if (meshHighlight.observerDefault) {
  77202. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  77203. }
  77204. delete this._meshes[mesh.uniqueId];
  77205. }
  77206. this._shouldRender = false;
  77207. for (var meshHighlightToCheck in this._meshes) {
  77208. if (this._meshes[meshHighlightToCheck]) {
  77209. this._shouldRender = true;
  77210. break;
  77211. }
  77212. }
  77213. };
  77214. /**
  77215. * Returns true if the layer contains information to display, otherwise false.
  77216. */
  77217. HighlightLayer.prototype.shouldRender = function () {
  77218. return this.isEnabled && this._shouldRender;
  77219. };
  77220. /**
  77221. * Sets the main texture desired size which is the closest power of two
  77222. * of the engine canvas size.
  77223. */
  77224. HighlightLayer.prototype.setMainTextureSize = function () {
  77225. if (this._options.mainTextureFixedSize) {
  77226. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  77227. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  77228. }
  77229. else {
  77230. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  77231. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  77232. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  77233. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  77234. }
  77235. };
  77236. /**
  77237. * Force the stencil to the normal expected value for none glowing parts
  77238. */
  77239. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  77240. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  77241. };
  77242. /**
  77243. * Dispose only the render target textures and post process.
  77244. */
  77245. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  77246. this._blurTexture.dispose();
  77247. this._mainTexture.dispose();
  77248. this._downSamplePostprocess.dispose();
  77249. this._horizontalBlurPostprocess.dispose();
  77250. this._verticalBlurPostprocess.dispose();
  77251. };
  77252. /**
  77253. * Dispose the highlight layer and free resources.
  77254. */
  77255. HighlightLayer.prototype.dispose = function () {
  77256. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77257. if (vertexBuffer) {
  77258. vertexBuffer.dispose();
  77259. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77260. }
  77261. if (this._indexBuffer) {
  77262. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77263. this._indexBuffer = null;
  77264. }
  77265. // Clean textures and post processes
  77266. this.disposeTextureAndPostProcesses();
  77267. if (this._meshes) {
  77268. // Clean mesh references
  77269. for (var id in this._meshes) {
  77270. var meshHighlight = this._meshes[id];
  77271. if (meshHighlight && meshHighlight.mesh) {
  77272. if (meshHighlight.observerHighlight) {
  77273. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  77274. }
  77275. if (meshHighlight.observerDefault) {
  77276. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  77277. }
  77278. }
  77279. }
  77280. this._meshes = null;
  77281. }
  77282. if (this._excludedMeshes) {
  77283. for (var id in this._excludedMeshes) {
  77284. var meshHighlight = this._excludedMeshes[id];
  77285. if (meshHighlight) {
  77286. if (meshHighlight.beforeRender) {
  77287. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  77288. }
  77289. if (meshHighlight.afterRender) {
  77290. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  77291. }
  77292. }
  77293. }
  77294. this._excludedMeshes = null;
  77295. }
  77296. // Remove from scene
  77297. var index = this._scene.highlightLayers.indexOf(this, 0);
  77298. if (index > -1) {
  77299. this._scene.highlightLayers.splice(index, 1);
  77300. }
  77301. // Callback
  77302. this.onDisposeObservable.notifyObservers(this);
  77303. this.onDisposeObservable.clear();
  77304. this.onBeforeRenderMainTextureObservable.clear();
  77305. this.onBeforeBlurObservable.clear();
  77306. this.onBeforeComposeObservable.clear();
  77307. this.onAfterComposeObservable.clear();
  77308. this.onSizeChangedObservable.clear();
  77309. };
  77310. /**
  77311. * The neutral color used during the preparation of the glow effect.
  77312. * This is black by default as the blend operation is a blend operation.
  77313. */
  77314. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  77315. /**
  77316. * Stencil value used for glowing meshes.
  77317. */
  77318. HighlightLayer.glowingMeshStencilReference = 0x02;
  77319. /**
  77320. * Stencil value used for the other meshes in the scene.
  77321. */
  77322. HighlightLayer.normalMeshStencilReference = 0x01;
  77323. return HighlightLayer;
  77324. }());
  77325. BABYLON.HighlightLayer = HighlightLayer;
  77326. })(BABYLON || (BABYLON = {}));
  77327. //# sourceMappingURL=babylon.highlightlayer.js.map
  77328. var BABYLON;
  77329. (function (BABYLON) {
  77330. /**
  77331. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  77332. */
  77333. var AssetTaskState;
  77334. (function (AssetTaskState) {
  77335. /**
  77336. * Initialization
  77337. */
  77338. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  77339. /**
  77340. * Running
  77341. */
  77342. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  77343. /**
  77344. * Done
  77345. */
  77346. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  77347. /**
  77348. * Error
  77349. */
  77350. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  77351. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  77352. /**
  77353. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  77354. */
  77355. var AbstractAssetTask = /** @class */ (function () {
  77356. /**
  77357. * Creates a new {BABYLON.AssetsManager}
  77358. * @param name defines the name of the task
  77359. */
  77360. function AbstractAssetTask(
  77361. /**
  77362. * Task name
  77363. */ name) {
  77364. this.name = name;
  77365. this._isCompleted = false;
  77366. this._taskState = AssetTaskState.INIT;
  77367. }
  77368. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  77369. /**
  77370. * Get if the task is completed
  77371. */
  77372. get: function () {
  77373. return this._isCompleted;
  77374. },
  77375. enumerable: true,
  77376. configurable: true
  77377. });
  77378. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  77379. /**
  77380. * Gets the current state of the task
  77381. */
  77382. get: function () {
  77383. return this._taskState;
  77384. },
  77385. enumerable: true,
  77386. configurable: true
  77387. });
  77388. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  77389. /**
  77390. * Gets the current error object (if task is in error)
  77391. */
  77392. get: function () {
  77393. return this._errorObject;
  77394. },
  77395. enumerable: true,
  77396. configurable: true
  77397. });
  77398. /**
  77399. * Internal only
  77400. * @ignore
  77401. */
  77402. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  77403. if (this._errorObject) {
  77404. return;
  77405. }
  77406. this._errorObject = {
  77407. message: message,
  77408. exception: exception
  77409. };
  77410. };
  77411. /**
  77412. * Execute the current task
  77413. * @param scene defines the scene where you want your assets to be loaded
  77414. * @param onSuccess is a callback called when the task is successfully executed
  77415. * @param onError is a callback called if an error occurs
  77416. */
  77417. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  77418. var _this = this;
  77419. this._taskState = AssetTaskState.RUNNING;
  77420. this.runTask(scene, function () {
  77421. _this.onDoneCallback(onSuccess, onError);
  77422. }, function (msg, exception) {
  77423. _this.onErrorCallback(onError, msg, exception);
  77424. });
  77425. };
  77426. /**
  77427. * Execute the current task
  77428. * @param scene defines the scene where you want your assets to be loaded
  77429. * @param onSuccess is a callback called when the task is successfully executed
  77430. * @param onError is a callback called if an error occurs
  77431. */
  77432. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77433. throw new Error("runTask is not implemented");
  77434. };
  77435. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  77436. this._taskState = AssetTaskState.ERROR;
  77437. this._errorObject = {
  77438. message: message,
  77439. exception: exception
  77440. };
  77441. if (this.onError) {
  77442. this.onError(this, message, exception);
  77443. }
  77444. onError();
  77445. };
  77446. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  77447. try {
  77448. this._taskState = AssetTaskState.DONE;
  77449. this._isCompleted = true;
  77450. if (this.onSuccess) {
  77451. this.onSuccess(this);
  77452. }
  77453. onSuccess();
  77454. }
  77455. catch (e) {
  77456. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  77457. }
  77458. };
  77459. return AbstractAssetTask;
  77460. }());
  77461. BABYLON.AbstractAssetTask = AbstractAssetTask;
  77462. /**
  77463. * Class used to share progress information about assets loading
  77464. */
  77465. var AssetsProgressEvent = /** @class */ (function () {
  77466. /**
  77467. * Creates a {BABYLON.AssetsProgressEvent}
  77468. * @param remainingCount defines the number of remaining tasks to process
  77469. * @param totalCount defines the total number of tasks
  77470. * @param task defines the task that was just processed
  77471. */
  77472. function AssetsProgressEvent(remainingCount, totalCount, task) {
  77473. this.remainingCount = remainingCount;
  77474. this.totalCount = totalCount;
  77475. this.task = task;
  77476. }
  77477. return AssetsProgressEvent;
  77478. }());
  77479. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  77480. /**
  77481. * Define a task used by {BABYLON.AssetsManager} to load meshes
  77482. */
  77483. var MeshAssetTask = /** @class */ (function (_super) {
  77484. __extends(MeshAssetTask, _super);
  77485. /**
  77486. * Creates a new {BABYLON.MeshAssetTask}
  77487. * @param name defines the name of the task
  77488. * @param meshesNames defines the list of mesh's names you want to load
  77489. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  77490. * @param sceneFilename defines the filename of the scene to load from
  77491. */
  77492. function MeshAssetTask(
  77493. /**
  77494. * Defines the name of the task
  77495. */
  77496. name,
  77497. /**
  77498. * Defines the list of mesh's names you want to load
  77499. */
  77500. meshesNames,
  77501. /**
  77502. * Defines the root url to use as a base to load your meshes and associated resources
  77503. */
  77504. rootUrl,
  77505. /**
  77506. * Defines the filename of the scene to load from
  77507. */
  77508. sceneFilename) {
  77509. var _this = _super.call(this, name) || this;
  77510. _this.name = name;
  77511. _this.meshesNames = meshesNames;
  77512. _this.rootUrl = rootUrl;
  77513. _this.sceneFilename = sceneFilename;
  77514. return _this;
  77515. }
  77516. /**
  77517. * Execute the current task
  77518. * @param scene defines the scene where you want your assets to be loaded
  77519. * @param onSuccess is a callback called when the task is successfully executed
  77520. * @param onError is a callback called if an error occurs
  77521. */
  77522. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77523. var _this = this;
  77524. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  77525. _this.loadedMeshes = meshes;
  77526. _this.loadedParticleSystems = particleSystems;
  77527. _this.loadedSkeletons = skeletons;
  77528. onSuccess();
  77529. }, null, function (scene, message, exception) {
  77530. onError(message, exception);
  77531. });
  77532. };
  77533. return MeshAssetTask;
  77534. }(AbstractAssetTask));
  77535. BABYLON.MeshAssetTask = MeshAssetTask;
  77536. /**
  77537. * Define a task used by {BABYLON.AssetsManager} to load text content
  77538. */
  77539. var TextFileAssetTask = /** @class */ (function (_super) {
  77540. __extends(TextFileAssetTask, _super);
  77541. /**
  77542. * Creates a new TextFileAssetTask object
  77543. * @param name defines the name of the task
  77544. * @param url defines the location of the file to load
  77545. */
  77546. function TextFileAssetTask(
  77547. /**
  77548. * Defines the name of the task
  77549. */
  77550. name,
  77551. /**
  77552. * Defines the location of the file to load
  77553. */
  77554. url) {
  77555. var _this = _super.call(this, name) || this;
  77556. _this.name = name;
  77557. _this.url = url;
  77558. return _this;
  77559. }
  77560. /**
  77561. * Execute the current task
  77562. * @param scene defines the scene where you want your assets to be loaded
  77563. * @param onSuccess is a callback called when the task is successfully executed
  77564. * @param onError is a callback called if an error occurs
  77565. */
  77566. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77567. var _this = this;
  77568. scene._loadFile(this.url, function (data) {
  77569. _this.text = data;
  77570. onSuccess();
  77571. }, undefined, false, true, function (request, exception) {
  77572. if (request) {
  77573. onError(request.status + " " + request.statusText, exception);
  77574. }
  77575. });
  77576. };
  77577. return TextFileAssetTask;
  77578. }(AbstractAssetTask));
  77579. BABYLON.TextFileAssetTask = TextFileAssetTask;
  77580. /**
  77581. * Define a task used by {BABYLON.AssetsManager} to load binary data
  77582. */
  77583. var BinaryFileAssetTask = /** @class */ (function (_super) {
  77584. __extends(BinaryFileAssetTask, _super);
  77585. /**
  77586. * Creates a new BinaryFileAssetTask object
  77587. * @param name defines the name of the new task
  77588. * @param url defines the location of the file to load
  77589. */
  77590. function BinaryFileAssetTask(
  77591. /**
  77592. * Defines the name of the task
  77593. */
  77594. name,
  77595. /**
  77596. * Defines the location of the file to load
  77597. */
  77598. url) {
  77599. var _this = _super.call(this, name) || this;
  77600. _this.name = name;
  77601. _this.url = url;
  77602. return _this;
  77603. }
  77604. /**
  77605. * Execute the current task
  77606. * @param scene defines the scene where you want your assets to be loaded
  77607. * @param onSuccess is a callback called when the task is successfully executed
  77608. * @param onError is a callback called if an error occurs
  77609. */
  77610. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77611. var _this = this;
  77612. scene._loadFile(this.url, function (data) {
  77613. _this.data = data;
  77614. onSuccess();
  77615. }, undefined, true, true, function (request, exception) {
  77616. if (request) {
  77617. onError(request.status + " " + request.statusText, exception);
  77618. }
  77619. });
  77620. };
  77621. return BinaryFileAssetTask;
  77622. }(AbstractAssetTask));
  77623. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  77624. /**
  77625. * Define a task used by {BABYLON.AssetsManager} to load images
  77626. */
  77627. var ImageAssetTask = /** @class */ (function (_super) {
  77628. __extends(ImageAssetTask, _super);
  77629. /**
  77630. * Creates a new ImageAssetTask
  77631. * @param name defines the name of the task
  77632. * @param url defines the location of the image to load
  77633. */
  77634. function ImageAssetTask(
  77635. /**
  77636. * Defines the name of the task
  77637. */
  77638. name,
  77639. /**
  77640. * Defines the location of the image to load
  77641. */
  77642. url) {
  77643. var _this = _super.call(this, name) || this;
  77644. _this.name = name;
  77645. _this.url = url;
  77646. return _this;
  77647. }
  77648. /**
  77649. * Execute the current task
  77650. * @param scene defines the scene where you want your assets to be loaded
  77651. * @param onSuccess is a callback called when the task is successfully executed
  77652. * @param onError is a callback called if an error occurs
  77653. */
  77654. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77655. var _this = this;
  77656. var img = new Image();
  77657. BABYLON.Tools.SetCorsBehavior(this.url, img);
  77658. img.onload = function () {
  77659. _this.image = img;
  77660. onSuccess();
  77661. };
  77662. img.onerror = function (err) {
  77663. onError("Error loading image", err);
  77664. };
  77665. img.src = this.url;
  77666. };
  77667. return ImageAssetTask;
  77668. }(AbstractAssetTask));
  77669. BABYLON.ImageAssetTask = ImageAssetTask;
  77670. /**
  77671. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  77672. */
  77673. var TextureAssetTask = /** @class */ (function (_super) {
  77674. __extends(TextureAssetTask, _super);
  77675. /**
  77676. * Creates a new TextureAssetTask object
  77677. * @param name defines the name of the task
  77678. * @param url defines the location of the file to load
  77679. * @param noMipmap defines if mipmap should not be generated (default is false)
  77680. * @param invertY defines if texture must be inverted on Y axis (default is false)
  77681. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  77682. */
  77683. function TextureAssetTask(
  77684. /**
  77685. * Defines the name of the task
  77686. */
  77687. name,
  77688. /**
  77689. * Defines the location of the file to load
  77690. */
  77691. url,
  77692. /**
  77693. * Defines if mipmap should not be generated (default is false)
  77694. */
  77695. noMipmap,
  77696. /**
  77697. * Defines if texture must be inverted on Y axis (default is false)
  77698. */
  77699. invertY,
  77700. /**
  77701. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  77702. */
  77703. samplingMode) {
  77704. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  77705. var _this = _super.call(this, name) || this;
  77706. _this.name = name;
  77707. _this.url = url;
  77708. _this.noMipmap = noMipmap;
  77709. _this.invertY = invertY;
  77710. _this.samplingMode = samplingMode;
  77711. return _this;
  77712. }
  77713. /**
  77714. * Execute the current task
  77715. * @param scene defines the scene where you want your assets to be loaded
  77716. * @param onSuccess is a callback called when the task is successfully executed
  77717. * @param onError is a callback called if an error occurs
  77718. */
  77719. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77720. var onload = function () {
  77721. onSuccess();
  77722. };
  77723. var onerror = function (message, exception) {
  77724. onError(message, exception);
  77725. };
  77726. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  77727. };
  77728. return TextureAssetTask;
  77729. }(AbstractAssetTask));
  77730. BABYLON.TextureAssetTask = TextureAssetTask;
  77731. /**
  77732. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  77733. */
  77734. var CubeTextureAssetTask = /** @class */ (function (_super) {
  77735. __extends(CubeTextureAssetTask, _super);
  77736. /**
  77737. * Creates a new CubeTextureAssetTask
  77738. * @param name defines the name of the task
  77739. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  77740. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  77741. * @param noMipmap defines if mipmaps should not be generated (default is false)
  77742. * @param files defines the explicit list of files (undefined by default)
  77743. */
  77744. function CubeTextureAssetTask(
  77745. /**
  77746. * Defines the name of the task
  77747. */
  77748. name,
  77749. /**
  77750. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  77751. */
  77752. url,
  77753. /**
  77754. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  77755. */
  77756. extensions,
  77757. /**
  77758. * Defines if mipmaps should not be generated (default is false)
  77759. */
  77760. noMipmap,
  77761. /**
  77762. * Defines the explicit list of files (undefined by default)
  77763. */
  77764. files) {
  77765. var _this = _super.call(this, name) || this;
  77766. _this.name = name;
  77767. _this.url = url;
  77768. _this.extensions = extensions;
  77769. _this.noMipmap = noMipmap;
  77770. _this.files = files;
  77771. return _this;
  77772. }
  77773. /**
  77774. * Execute the current task
  77775. * @param scene defines the scene where you want your assets to be loaded
  77776. * @param onSuccess is a callback called when the task is successfully executed
  77777. * @param onError is a callback called if an error occurs
  77778. */
  77779. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77780. var onload = function () {
  77781. onSuccess();
  77782. };
  77783. var onerror = function (message, exception) {
  77784. onError(message, exception);
  77785. };
  77786. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  77787. };
  77788. return CubeTextureAssetTask;
  77789. }(AbstractAssetTask));
  77790. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  77791. /**
  77792. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  77793. */
  77794. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  77795. __extends(HDRCubeTextureAssetTask, _super);
  77796. /**
  77797. * Creates a new HDRCubeTextureAssetTask object
  77798. * @param name defines the name of the task
  77799. * @param url defines the location of the file to load
  77800. * @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.
  77801. * @param noMipmap defines if mipmaps should not be generated (default is false)
  77802. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  77803. * @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)
  77804. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  77805. */
  77806. function HDRCubeTextureAssetTask(
  77807. /**
  77808. * Defines the name of the task
  77809. */
  77810. name,
  77811. /**
  77812. * Defines the location of the file to load
  77813. */
  77814. url,
  77815. /**
  77816. * 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.
  77817. */
  77818. size,
  77819. /**
  77820. * Defines if mipmaps should not be generated (default is false)
  77821. */
  77822. noMipmap,
  77823. /**
  77824. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  77825. */
  77826. generateHarmonics,
  77827. /**
  77828. * 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)
  77829. */
  77830. useInGammaSpace,
  77831. /**
  77832. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  77833. */
  77834. usePMREMGenerator) {
  77835. if (noMipmap === void 0) { noMipmap = false; }
  77836. if (generateHarmonics === void 0) { generateHarmonics = true; }
  77837. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  77838. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  77839. var _this = _super.call(this, name) || this;
  77840. _this.name = name;
  77841. _this.url = url;
  77842. _this.size = size;
  77843. _this.noMipmap = noMipmap;
  77844. _this.generateHarmonics = generateHarmonics;
  77845. _this.useInGammaSpace = useInGammaSpace;
  77846. _this.usePMREMGenerator = usePMREMGenerator;
  77847. return _this;
  77848. }
  77849. /**
  77850. * Execute the current task
  77851. * @param scene defines the scene where you want your assets to be loaded
  77852. * @param onSuccess is a callback called when the task is successfully executed
  77853. * @param onError is a callback called if an error occurs
  77854. */
  77855. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  77856. var onload = function () {
  77857. onSuccess();
  77858. };
  77859. var onerror = function (message, exception) {
  77860. onError(message, exception);
  77861. };
  77862. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  77863. };
  77864. return HDRCubeTextureAssetTask;
  77865. }(AbstractAssetTask));
  77866. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  77867. /**
  77868. * This class can be used to easily import assets into a scene
  77869. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  77870. */
  77871. var AssetsManager = /** @class */ (function () {
  77872. /**
  77873. * Creates a new AssetsManager
  77874. * @param scene defines the scene to work on
  77875. */
  77876. function AssetsManager(scene) {
  77877. this._isLoading = false;
  77878. this._tasks = new Array();
  77879. this._waitingTasksCount = 0;
  77880. this._totalTasksCount = 0;
  77881. /**
  77882. * Observable called when all tasks are processed
  77883. */
  77884. this.onTaskSuccessObservable = new BABYLON.Observable();
  77885. /**
  77886. * Observable called when a task had an error
  77887. */
  77888. this.onTaskErrorObservable = new BABYLON.Observable();
  77889. /**
  77890. * Observable called when a task is successful
  77891. */
  77892. this.onTasksDoneObservable = new BABYLON.Observable();
  77893. /**
  77894. * Observable called when a task is done (whatever the result is)
  77895. */
  77896. this.onProgressObservable = new BABYLON.Observable();
  77897. /**
  77898. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  77899. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  77900. */
  77901. this.useDefaultLoadingScreen = true;
  77902. this._scene = scene;
  77903. }
  77904. /**
  77905. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  77906. * @param taskName defines the name of the new task
  77907. * @param meshesNames defines the name of meshes to load
  77908. * @param rootUrl defines the root url to use to locate files
  77909. * @param sceneFilename defines the filename of the scene file
  77910. * @returns a new {BABYLON.MeshAssetTask} object
  77911. */
  77912. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  77913. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  77914. this._tasks.push(task);
  77915. return task;
  77916. };
  77917. /**
  77918. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  77919. * @param taskName defines the name of the new task
  77920. * @param url defines the url of the file to load
  77921. * @returns a new {BABYLON.TextFileAssetTask} object
  77922. */
  77923. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  77924. var task = new TextFileAssetTask(taskName, url);
  77925. this._tasks.push(task);
  77926. return task;
  77927. };
  77928. /**
  77929. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  77930. * @param taskName defines the name of the new task
  77931. * @param url defines the url of the file to load
  77932. * @returns a new {BABYLON.BinaryFileAssetTask} object
  77933. */
  77934. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  77935. var task = new BinaryFileAssetTask(taskName, url);
  77936. this._tasks.push(task);
  77937. return task;
  77938. };
  77939. /**
  77940. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  77941. * @param taskName defines the name of the new task
  77942. * @param url defines the url of the file to load
  77943. * @returns a new {BABYLON.ImageAssetTask} object
  77944. */
  77945. AssetsManager.prototype.addImageTask = function (taskName, url) {
  77946. var task = new ImageAssetTask(taskName, url);
  77947. this._tasks.push(task);
  77948. return task;
  77949. };
  77950. /**
  77951. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  77952. * @param taskName defines the name of the new task
  77953. * @param url defines the url of the file to load
  77954. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  77955. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  77956. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  77957. * @returns a new {BABYLON.TextureAssetTask} object
  77958. */
  77959. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  77960. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  77961. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  77962. this._tasks.push(task);
  77963. return task;
  77964. };
  77965. /**
  77966. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  77967. * @param taskName defines the name of the new task
  77968. * @param url defines the url of the file to load
  77969. * @param extensions defines the extension to use to load the cube map (can be null)
  77970. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  77971. * @param files defines the list of files to load (can be null)
  77972. * @returns a new {BABYLON.CubeTextureAssetTask} object
  77973. */
  77974. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  77975. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  77976. this._tasks.push(task);
  77977. return task;
  77978. };
  77979. /**
  77980. *
  77981. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  77982. * @param taskName defines the name of the new task
  77983. * @param url defines the url of the file to load
  77984. * @param size defines the size you want for the cubemap (can be null)
  77985. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  77986. * @param generateHarmonics defines if you want to automatically generate (true by default)
  77987. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  77988. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  77989. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  77990. */
  77991. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  77992. if (noMipmap === void 0) { noMipmap = false; }
  77993. if (generateHarmonics === void 0) { generateHarmonics = true; }
  77994. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  77995. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  77996. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  77997. this._tasks.push(task);
  77998. return task;
  77999. };
  78000. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  78001. var _this = this;
  78002. this._waitingTasksCount--;
  78003. try {
  78004. if (task.taskState === AssetTaskState.DONE) {
  78005. // Let's remove successfull tasks
  78006. BABYLON.Tools.SetImmediate(function () {
  78007. var index = _this._tasks.indexOf(task);
  78008. if (index > -1) {
  78009. _this._tasks.splice(index, 1);
  78010. }
  78011. });
  78012. }
  78013. if (this.onProgress) {
  78014. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  78015. }
  78016. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  78017. }
  78018. catch (e) {
  78019. BABYLON.Tools.Error("Error running progress callbacks.");
  78020. console.log(e);
  78021. }
  78022. if (this._waitingTasksCount === 0) {
  78023. try {
  78024. if (this.onFinish) {
  78025. this.onFinish(this._tasks);
  78026. }
  78027. this.onTasksDoneObservable.notifyObservers(this._tasks);
  78028. }
  78029. catch (e) {
  78030. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  78031. console.log(e);
  78032. }
  78033. this._isLoading = false;
  78034. this._scene.getEngine().hideLoadingUI();
  78035. }
  78036. };
  78037. AssetsManager.prototype._runTask = function (task) {
  78038. var _this = this;
  78039. var done = function () {
  78040. try {
  78041. if (_this.onTaskSuccess) {
  78042. _this.onTaskSuccess(task);
  78043. }
  78044. _this.onTaskSuccessObservable.notifyObservers(task);
  78045. _this._decreaseWaitingTasksCount(task);
  78046. }
  78047. catch (e) {
  78048. error("Error executing task success callbacks", e);
  78049. }
  78050. };
  78051. var error = function (message, exception) {
  78052. task._setErrorObject(message, exception);
  78053. if (_this.onTaskError) {
  78054. _this.onTaskError(task);
  78055. }
  78056. _this.onTaskErrorObservable.notifyObservers(task);
  78057. _this._decreaseWaitingTasksCount(task);
  78058. };
  78059. task.run(this._scene, done, error);
  78060. };
  78061. /**
  78062. * Reset the {BABYLON.AssetsManager} and remove all tasks
  78063. * @return the current instance of the {BABYLON.AssetsManager}
  78064. */
  78065. AssetsManager.prototype.reset = function () {
  78066. this._isLoading = false;
  78067. this._tasks = new Array();
  78068. return this;
  78069. };
  78070. /**
  78071. * Start the loading process
  78072. * @return the current instance of the {BABYLON.AssetsManager}
  78073. */
  78074. AssetsManager.prototype.load = function () {
  78075. if (this._isLoading) {
  78076. return this;
  78077. }
  78078. this._isLoading = true;
  78079. this._waitingTasksCount = this._tasks.length;
  78080. this._totalTasksCount = this._tasks.length;
  78081. if (this._waitingTasksCount === 0) {
  78082. if (this.onFinish) {
  78083. this.onFinish(this._tasks);
  78084. }
  78085. this.onTasksDoneObservable.notifyObservers(this._tasks);
  78086. return this;
  78087. }
  78088. if (this.useDefaultLoadingScreen) {
  78089. this._scene.getEngine().displayLoadingUI();
  78090. }
  78091. for (var index = 0; index < this._tasks.length; index++) {
  78092. var task = this._tasks[index];
  78093. this._runTask(task);
  78094. }
  78095. return this;
  78096. };
  78097. return AssetsManager;
  78098. }());
  78099. BABYLON.AssetsManager = AssetsManager;
  78100. })(BABYLON || (BABYLON = {}));
  78101. //# sourceMappingURL=babylon.assetsManager.js.map
  78102. var BABYLON;
  78103. (function (BABYLON) {
  78104. var serializedGeometries = [];
  78105. var serializeGeometry = function (geometry, serializationGeometries) {
  78106. if (serializedGeometries[geometry.id]) {
  78107. return;
  78108. }
  78109. if (geometry.doNotSerialize) {
  78110. return;
  78111. }
  78112. if (geometry instanceof BABYLON.BoxGeometry) {
  78113. serializationGeometries.boxes.push(geometry.serialize());
  78114. }
  78115. else if (geometry instanceof BABYLON.SphereGeometry) {
  78116. serializationGeometries.spheres.push(geometry.serialize());
  78117. }
  78118. else if (geometry instanceof BABYLON.CylinderGeometry) {
  78119. serializationGeometries.cylinders.push(geometry.serialize());
  78120. }
  78121. else if (geometry instanceof BABYLON.TorusGeometry) {
  78122. serializationGeometries.toruses.push(geometry.serialize());
  78123. }
  78124. else if (geometry instanceof BABYLON.GroundGeometry) {
  78125. serializationGeometries.grounds.push(geometry.serialize());
  78126. }
  78127. else if (geometry instanceof BABYLON.Plane) {
  78128. serializationGeometries.planes.push(geometry.serialize());
  78129. }
  78130. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  78131. serializationGeometries.torusKnots.push(geometry.serialize());
  78132. }
  78133. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  78134. throw new Error("Unknown primitive type");
  78135. }
  78136. else {
  78137. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  78138. }
  78139. serializedGeometries[geometry.id] = true;
  78140. };
  78141. var serializeMesh = function (mesh, serializationScene) {
  78142. var serializationObject = {};
  78143. // Geometry
  78144. var geometry = mesh._geometry;
  78145. if (geometry) {
  78146. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  78147. // 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
  78148. serializeGeometry(geometry, serializationScene.geometries);
  78149. }
  78150. }
  78151. // Custom
  78152. if (mesh.serialize) {
  78153. mesh.serialize(serializationObject);
  78154. }
  78155. return serializationObject;
  78156. };
  78157. var finalizeSingleMesh = function (mesh, serializationObject) {
  78158. //only works if the mesh is already loaded
  78159. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  78160. //serialize material
  78161. if (mesh.material) {
  78162. if (mesh.material instanceof BABYLON.StandardMaterial) {
  78163. serializationObject.materials = serializationObject.materials || [];
  78164. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  78165. serializationObject.materials.push(mesh.material.serialize());
  78166. }
  78167. }
  78168. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  78169. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  78170. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  78171. serializationObject.multiMaterials.push(mesh.material.serialize());
  78172. }
  78173. }
  78174. }
  78175. //serialize geometry
  78176. var geometry = mesh._geometry;
  78177. if (geometry) {
  78178. if (!serializationObject.geometries) {
  78179. serializationObject.geometries = {};
  78180. serializationObject.geometries.boxes = [];
  78181. serializationObject.geometries.spheres = [];
  78182. serializationObject.geometries.cylinders = [];
  78183. serializationObject.geometries.toruses = [];
  78184. serializationObject.geometries.grounds = [];
  78185. serializationObject.geometries.planes = [];
  78186. serializationObject.geometries.torusKnots = [];
  78187. serializationObject.geometries.vertexData = [];
  78188. }
  78189. serializeGeometry(geometry, serializationObject.geometries);
  78190. }
  78191. // Skeletons
  78192. if (mesh.skeleton) {
  78193. serializationObject.skeletons = serializationObject.skeletons || [];
  78194. serializationObject.skeletons.push(mesh.skeleton.serialize());
  78195. }
  78196. //serialize the actual mesh
  78197. serializationObject.meshes = serializationObject.meshes || [];
  78198. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  78199. }
  78200. };
  78201. var SceneSerializer = /** @class */ (function () {
  78202. function SceneSerializer() {
  78203. }
  78204. SceneSerializer.ClearCache = function () {
  78205. serializedGeometries = [];
  78206. };
  78207. SceneSerializer.Serialize = function (scene) {
  78208. var serializationObject = {};
  78209. SceneSerializer.ClearCache();
  78210. // Scene
  78211. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  78212. serializationObject.autoClear = scene.autoClear;
  78213. serializationObject.clearColor = scene.clearColor.asArray();
  78214. serializationObject.ambientColor = scene.ambientColor.asArray();
  78215. serializationObject.gravity = scene.gravity.asArray();
  78216. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  78217. serializationObject.workerCollisions = scene.workerCollisions;
  78218. // Fog
  78219. if (scene.fogMode && scene.fogMode !== 0) {
  78220. serializationObject.fogMode = scene.fogMode;
  78221. serializationObject.fogColor = scene.fogColor.asArray();
  78222. serializationObject.fogStart = scene.fogStart;
  78223. serializationObject.fogEnd = scene.fogEnd;
  78224. serializationObject.fogDensity = scene.fogDensity;
  78225. }
  78226. //Physics
  78227. if (scene.isPhysicsEnabled()) {
  78228. var physicEngine = scene.getPhysicsEngine();
  78229. if (physicEngine) {
  78230. serializationObject.physicsEnabled = true;
  78231. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  78232. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  78233. }
  78234. }
  78235. // Metadata
  78236. if (scene.metadata) {
  78237. serializationObject.metadata = scene.metadata;
  78238. }
  78239. // Morph targets
  78240. serializationObject.morphTargetManagers = [];
  78241. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  78242. var abstractMesh = _a[_i];
  78243. var manager = abstractMesh.morphTargetManager;
  78244. if (manager) {
  78245. serializationObject.morphTargetManagers.push(manager.serialize());
  78246. }
  78247. }
  78248. // Lights
  78249. serializationObject.lights = [];
  78250. var index;
  78251. var light;
  78252. for (index = 0; index < scene.lights.length; index++) {
  78253. light = scene.lights[index];
  78254. if (!light.doNotSerialize) {
  78255. serializationObject.lights.push(light.serialize());
  78256. }
  78257. }
  78258. // Cameras
  78259. serializationObject.cameras = [];
  78260. for (index = 0; index < scene.cameras.length; index++) {
  78261. var camera = scene.cameras[index];
  78262. if (!camera.doNotSerialize) {
  78263. serializationObject.cameras.push(camera.serialize());
  78264. }
  78265. }
  78266. if (scene.activeCamera) {
  78267. serializationObject.activeCameraID = scene.activeCamera.id;
  78268. }
  78269. // Animations
  78270. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  78271. // Materials
  78272. serializationObject.materials = [];
  78273. serializationObject.multiMaterials = [];
  78274. var material;
  78275. for (index = 0; index < scene.materials.length; index++) {
  78276. material = scene.materials[index];
  78277. if (!material.doNotSerialize) {
  78278. serializationObject.materials.push(material.serialize());
  78279. }
  78280. }
  78281. // MultiMaterials
  78282. serializationObject.multiMaterials = [];
  78283. for (index = 0; index < scene.multiMaterials.length; index++) {
  78284. var multiMaterial = scene.multiMaterials[index];
  78285. serializationObject.multiMaterials.push(multiMaterial.serialize());
  78286. }
  78287. // Environment texture
  78288. if (scene.environmentTexture) {
  78289. serializationObject.environmentTexture = scene.environmentTexture.name;
  78290. }
  78291. // Skeletons
  78292. serializationObject.skeletons = [];
  78293. for (index = 0; index < scene.skeletons.length; index++) {
  78294. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  78295. }
  78296. // Transform nodes
  78297. serializationObject.transformNodes = [];
  78298. for (index = 0; index < scene.transformNodes.length; index++) {
  78299. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  78300. }
  78301. // Geometries
  78302. serializationObject.geometries = {};
  78303. serializationObject.geometries.boxes = [];
  78304. serializationObject.geometries.spheres = [];
  78305. serializationObject.geometries.cylinders = [];
  78306. serializationObject.geometries.toruses = [];
  78307. serializationObject.geometries.grounds = [];
  78308. serializationObject.geometries.planes = [];
  78309. serializationObject.geometries.torusKnots = [];
  78310. serializationObject.geometries.vertexData = [];
  78311. serializedGeometries = [];
  78312. var geometries = scene.getGeometries();
  78313. for (index = 0; index < geometries.length; index++) {
  78314. var geometry = geometries[index];
  78315. if (geometry.isReady()) {
  78316. serializeGeometry(geometry, serializationObject.geometries);
  78317. }
  78318. }
  78319. // Meshes
  78320. serializationObject.meshes = [];
  78321. for (index = 0; index < scene.meshes.length; index++) {
  78322. var abstractMesh = scene.meshes[index];
  78323. if (abstractMesh instanceof BABYLON.Mesh) {
  78324. var mesh = abstractMesh;
  78325. if (!mesh.doNotSerialize) {
  78326. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  78327. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  78328. }
  78329. }
  78330. }
  78331. }
  78332. // Particles Systems
  78333. serializationObject.particleSystems = [];
  78334. for (index = 0; index < scene.particleSystems.length; index++) {
  78335. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  78336. }
  78337. // Lens flares
  78338. serializationObject.lensFlareSystems = [];
  78339. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  78340. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  78341. }
  78342. // Shadows
  78343. serializationObject.shadowGenerators = [];
  78344. for (index = 0; index < scene.lights.length; index++) {
  78345. light = scene.lights[index];
  78346. var shadowGenerator = light.getShadowGenerator();
  78347. if (shadowGenerator) {
  78348. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  78349. }
  78350. }
  78351. // Action Manager
  78352. if (scene.actionManager) {
  78353. serializationObject.actions = scene.actionManager.serialize("scene");
  78354. }
  78355. // Audio
  78356. serializationObject.sounds = [];
  78357. for (index = 0; index < scene.soundTracks.length; index++) {
  78358. var soundtrack = scene.soundTracks[index];
  78359. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  78360. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  78361. }
  78362. }
  78363. return serializationObject;
  78364. };
  78365. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  78366. if (withParents === void 0) { withParents = false; }
  78367. if (withChildren === void 0) { withChildren = false; }
  78368. var serializationObject = {};
  78369. SceneSerializer.ClearCache();
  78370. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  78371. if (withParents || withChildren) {
  78372. //deliberate for loop! not for each, appended should be processed as well.
  78373. for (var i = 0; i < toSerialize.length; ++i) {
  78374. if (withChildren) {
  78375. toSerialize[i].getDescendants().forEach(function (node) {
  78376. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  78377. toSerialize.push(node);
  78378. }
  78379. });
  78380. }
  78381. //make sure the array doesn't contain the object already
  78382. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  78383. toSerialize.push(toSerialize[i].parent);
  78384. }
  78385. }
  78386. }
  78387. toSerialize.forEach(function (mesh) {
  78388. finalizeSingleMesh(mesh, serializationObject);
  78389. });
  78390. return serializationObject;
  78391. };
  78392. return SceneSerializer;
  78393. }());
  78394. BABYLON.SceneSerializer = SceneSerializer;
  78395. })(BABYLON || (BABYLON = {}));
  78396. //# sourceMappingURL=babylon.sceneSerializer.js.map
  78397. var BABYLON;
  78398. (function (BABYLON) {
  78399. var ReflectionProbe = /** @class */ (function () {
  78400. function ReflectionProbe(name, size, scene, generateMipMaps) {
  78401. if (generateMipMaps === void 0) { generateMipMaps = true; }
  78402. var _this = this;
  78403. this.name = name;
  78404. this._viewMatrix = BABYLON.Matrix.Identity();
  78405. this._target = BABYLON.Vector3.Zero();
  78406. this._add = BABYLON.Vector3.Zero();
  78407. this.invertYAxis = false;
  78408. this.position = BABYLON.Vector3.Zero();
  78409. this._scene = scene;
  78410. this._scene.reflectionProbes.push(this);
  78411. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  78412. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  78413. switch (faceIndex) {
  78414. case 0:
  78415. _this._add.copyFromFloats(1, 0, 0);
  78416. break;
  78417. case 1:
  78418. _this._add.copyFromFloats(-1, 0, 0);
  78419. break;
  78420. case 2:
  78421. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  78422. break;
  78423. case 3:
  78424. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  78425. break;
  78426. case 4:
  78427. _this._add.copyFromFloats(0, 0, 1);
  78428. break;
  78429. case 5:
  78430. _this._add.copyFromFloats(0, 0, -1);
  78431. break;
  78432. }
  78433. if (_this._attachedMesh) {
  78434. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  78435. }
  78436. _this.position.addToRef(_this._add, _this._target);
  78437. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  78438. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  78439. scene._forcedViewPosition = _this.position;
  78440. });
  78441. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  78442. scene._forcedViewPosition = null;
  78443. scene.updateTransformMatrix(true);
  78444. });
  78445. if (scene.activeCamera) {
  78446. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  78447. }
  78448. }
  78449. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  78450. get: function () {
  78451. return this._renderTargetTexture.samples;
  78452. },
  78453. set: function (value) {
  78454. this._renderTargetTexture.samples = value;
  78455. },
  78456. enumerable: true,
  78457. configurable: true
  78458. });
  78459. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  78460. get: function () {
  78461. return this._renderTargetTexture.refreshRate;
  78462. },
  78463. set: function (value) {
  78464. this._renderTargetTexture.refreshRate = value;
  78465. },
  78466. enumerable: true,
  78467. configurable: true
  78468. });
  78469. ReflectionProbe.prototype.getScene = function () {
  78470. return this._scene;
  78471. };
  78472. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  78473. get: function () {
  78474. return this._renderTargetTexture;
  78475. },
  78476. enumerable: true,
  78477. configurable: true
  78478. });
  78479. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  78480. get: function () {
  78481. return this._renderTargetTexture.renderList;
  78482. },
  78483. enumerable: true,
  78484. configurable: true
  78485. });
  78486. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  78487. this._attachedMesh = mesh;
  78488. };
  78489. /**
  78490. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  78491. *
  78492. * @param renderingGroupId The rendering group id corresponding to its index
  78493. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  78494. */
  78495. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  78496. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  78497. };
  78498. ReflectionProbe.prototype.dispose = function () {
  78499. var index = this._scene.reflectionProbes.indexOf(this);
  78500. if (index !== -1) {
  78501. // Remove from the scene if found
  78502. this._scene.reflectionProbes.splice(index, 1);
  78503. }
  78504. if (this._renderTargetTexture) {
  78505. this._renderTargetTexture.dispose();
  78506. this._renderTargetTexture = null;
  78507. }
  78508. };
  78509. return ReflectionProbe;
  78510. }());
  78511. BABYLON.ReflectionProbe = ReflectionProbe;
  78512. })(BABYLON || (BABYLON = {}));
  78513. //# sourceMappingURL=babylon.reflectionProbe.js.map
  78514. var BABYLON;
  78515. (function (BABYLON) {
  78516. var Layer = /** @class */ (function () {
  78517. function Layer(name, imgUrl, scene, isBackground, color) {
  78518. this.name = name;
  78519. this.scale = new BABYLON.Vector2(1, 1);
  78520. this.offset = new BABYLON.Vector2(0, 0);
  78521. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  78522. this.layerMask = 0x0FFFFFFF;
  78523. this._vertexBuffers = {};
  78524. // Events
  78525. /**
  78526. * An event triggered when the layer is disposed.
  78527. * @type {BABYLON.Observable}
  78528. */
  78529. this.onDisposeObservable = new BABYLON.Observable();
  78530. /**
  78531. * An event triggered before rendering the scene
  78532. * @type {BABYLON.Observable}
  78533. */
  78534. this.onBeforeRenderObservable = new BABYLON.Observable();
  78535. /**
  78536. * An event triggered after rendering the scene
  78537. * @type {BABYLON.Observable}
  78538. */
  78539. this.onAfterRenderObservable = new BABYLON.Observable();
  78540. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  78541. this.isBackground = isBackground === undefined ? true : isBackground;
  78542. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  78543. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  78544. this._scene.layers.push(this);
  78545. var engine = this._scene.getEngine();
  78546. // VBO
  78547. var vertices = [];
  78548. vertices.push(1, 1);
  78549. vertices.push(-1, 1);
  78550. vertices.push(-1, -1);
  78551. vertices.push(1, -1);
  78552. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  78553. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  78554. this._createIndexBuffer();
  78555. // Effects
  78556. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  78557. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  78558. }
  78559. Object.defineProperty(Layer.prototype, "onDispose", {
  78560. set: function (callback) {
  78561. if (this._onDisposeObserver) {
  78562. this.onDisposeObservable.remove(this._onDisposeObserver);
  78563. }
  78564. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  78565. },
  78566. enumerable: true,
  78567. configurable: true
  78568. });
  78569. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  78570. set: function (callback) {
  78571. if (this._onBeforeRenderObserver) {
  78572. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  78573. }
  78574. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  78575. },
  78576. enumerable: true,
  78577. configurable: true
  78578. });
  78579. Object.defineProperty(Layer.prototype, "onAfterRender", {
  78580. set: function (callback) {
  78581. if (this._onAfterRenderObserver) {
  78582. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  78583. }
  78584. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  78585. },
  78586. enumerable: true,
  78587. configurable: true
  78588. });
  78589. Layer.prototype._createIndexBuffer = function () {
  78590. var engine = this._scene.getEngine();
  78591. // Indices
  78592. var indices = [];
  78593. indices.push(0);
  78594. indices.push(1);
  78595. indices.push(2);
  78596. indices.push(0);
  78597. indices.push(2);
  78598. indices.push(3);
  78599. this._indexBuffer = engine.createIndexBuffer(indices);
  78600. };
  78601. Layer.prototype._rebuild = function () {
  78602. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78603. if (vb) {
  78604. vb._rebuild();
  78605. }
  78606. this._createIndexBuffer();
  78607. };
  78608. Layer.prototype.render = function () {
  78609. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  78610. // Check
  78611. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  78612. return;
  78613. var engine = this._scene.getEngine();
  78614. this.onBeforeRenderObservable.notifyObservers(this);
  78615. // Render
  78616. engine.enableEffect(currentEffect);
  78617. engine.setState(false);
  78618. // Texture
  78619. currentEffect.setTexture("textureSampler", this.texture);
  78620. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  78621. // Color
  78622. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  78623. // Scale / offset
  78624. currentEffect.setVector2("offset", this.offset);
  78625. currentEffect.setVector2("scale", this.scale);
  78626. // VBOs
  78627. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  78628. // Draw order
  78629. if (!this.alphaTest) {
  78630. engine.setAlphaMode(this.alphaBlendingMode);
  78631. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78632. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78633. }
  78634. else {
  78635. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78636. }
  78637. this.onAfterRenderObservable.notifyObservers(this);
  78638. };
  78639. Layer.prototype.dispose = function () {
  78640. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78641. if (vertexBuffer) {
  78642. vertexBuffer.dispose();
  78643. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78644. }
  78645. if (this._indexBuffer) {
  78646. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78647. this._indexBuffer = null;
  78648. }
  78649. if (this.texture) {
  78650. this.texture.dispose();
  78651. this.texture = null;
  78652. }
  78653. // Remove from scene
  78654. var index = this._scene.layers.indexOf(this);
  78655. this._scene.layers.splice(index, 1);
  78656. // Callback
  78657. this.onDisposeObservable.notifyObservers(this);
  78658. this.onDisposeObservable.clear();
  78659. this.onAfterRenderObservable.clear();
  78660. this.onBeforeRenderObservable.clear();
  78661. };
  78662. return Layer;
  78663. }());
  78664. BABYLON.Layer = Layer;
  78665. })(BABYLON || (BABYLON = {}));
  78666. //# sourceMappingURL=babylon.layer.js.map
  78667. var BABYLON;
  78668. (function (BABYLON) {
  78669. var TextureTools = /** @class */ (function () {
  78670. function TextureTools() {
  78671. }
  78672. /**
  78673. * Uses the GPU to create a copy texture rescaled at a given size
  78674. * @param texture Texture to copy from
  78675. * @param width Desired width
  78676. * @param height Desired height
  78677. * @return Generated texture
  78678. */
  78679. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  78680. if (useBilinearMode === void 0) { useBilinearMode = true; }
  78681. var scene = texture.getScene();
  78682. var engine = scene.getEngine();
  78683. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  78684. rtt.wrapU = texture.wrapU;
  78685. rtt.wrapV = texture.wrapV;
  78686. rtt.uOffset = texture.uOffset;
  78687. rtt.vOffset = texture.vOffset;
  78688. rtt.uScale = texture.uScale;
  78689. rtt.vScale = texture.vScale;
  78690. rtt.uAng = texture.uAng;
  78691. rtt.vAng = texture.vAng;
  78692. rtt.wAng = texture.wAng;
  78693. rtt.coordinatesIndex = texture.coordinatesIndex;
  78694. rtt.level = texture.level;
  78695. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  78696. rtt._texture.isReady = false;
  78697. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78698. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78699. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78700. passPostProcess.getEffect().executeWhenCompiled(function () {
  78701. passPostProcess.onApply = function (effect) {
  78702. effect.setTexture("textureSampler", texture);
  78703. };
  78704. var internalTexture = rtt.getInternalTexture();
  78705. if (internalTexture) {
  78706. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  78707. engine.unBindFramebuffer(internalTexture);
  78708. rtt.disposeFramebufferObjects();
  78709. passPostProcess.dispose();
  78710. internalTexture.isReady = true;
  78711. }
  78712. });
  78713. return rtt;
  78714. };
  78715. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  78716. if (!scene._environmentBRDFTexture) {
  78717. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78718. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78719. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78720. scene._environmentBRDFTexture = texture;
  78721. }
  78722. return scene._environmentBRDFTexture;
  78723. };
  78724. 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=";
  78725. return TextureTools;
  78726. }());
  78727. BABYLON.TextureTools = TextureTools;
  78728. })(BABYLON || (BABYLON = {}));
  78729. //# sourceMappingURL=babylon.textureTools.js.map
  78730. var BABYLON;
  78731. (function (BABYLON) {
  78732. var FramingBehavior = /** @class */ (function () {
  78733. function FramingBehavior() {
  78734. this._mode = FramingBehavior.FitFrustumSidesMode;
  78735. this._radiusScale = 1.0;
  78736. this._positionScale = 0.5;
  78737. this._defaultElevation = 0.3;
  78738. this._elevationReturnTime = 1500;
  78739. this._elevationReturnWaitTime = 1000;
  78740. this._zoomStopsAnimation = false;
  78741. this._framingTime = 1500;
  78742. this._isPointerDown = false;
  78743. this._lastInteractionTime = -Infinity;
  78744. // Framing control
  78745. this._animatables = new Array();
  78746. this._betaIsAnimating = false;
  78747. }
  78748. Object.defineProperty(FramingBehavior.prototype, "name", {
  78749. get: function () {
  78750. return "Framing";
  78751. },
  78752. enumerable: true,
  78753. configurable: true
  78754. });
  78755. Object.defineProperty(FramingBehavior.prototype, "mode", {
  78756. /**
  78757. * Gets current mode used by the behavior.
  78758. */
  78759. get: function () {
  78760. return this._mode;
  78761. },
  78762. /**
  78763. * Sets the current mode used by the behavior
  78764. */
  78765. set: function (mode) {
  78766. this._mode = mode;
  78767. },
  78768. enumerable: true,
  78769. configurable: true
  78770. });
  78771. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  78772. /**
  78773. * Gets the scale applied to the radius
  78774. */
  78775. get: function () {
  78776. return this._radiusScale;
  78777. },
  78778. /**
  78779. * Sets the scale applied to the radius (1 by default)
  78780. */
  78781. set: function (radius) {
  78782. this._radiusScale = radius;
  78783. },
  78784. enumerable: true,
  78785. configurable: true
  78786. });
  78787. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  78788. /**
  78789. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  78790. */
  78791. get: function () {
  78792. return this._positionScale;
  78793. },
  78794. /**
  78795. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  78796. */
  78797. set: function (scale) {
  78798. this._positionScale = scale;
  78799. },
  78800. enumerable: true,
  78801. configurable: true
  78802. });
  78803. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  78804. /**
  78805. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  78806. * behaviour is triggered, in radians.
  78807. */
  78808. get: function () {
  78809. return this._defaultElevation;
  78810. },
  78811. /**
  78812. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  78813. * behaviour is triggered, in radians.
  78814. */
  78815. set: function (elevation) {
  78816. this._defaultElevation = elevation;
  78817. },
  78818. enumerable: true,
  78819. configurable: true
  78820. });
  78821. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  78822. /**
  78823. * Gets the time (in milliseconds) taken to return to the default beta position.
  78824. * Negative value indicates camera should not return to default.
  78825. */
  78826. get: function () {
  78827. return this._elevationReturnTime;
  78828. },
  78829. /**
  78830. * Sets the time (in milliseconds) taken to return to the default beta position.
  78831. * Negative value indicates camera should not return to default.
  78832. */
  78833. set: function (speed) {
  78834. this._elevationReturnTime = speed;
  78835. },
  78836. enumerable: true,
  78837. configurable: true
  78838. });
  78839. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  78840. /**
  78841. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  78842. */
  78843. get: function () {
  78844. return this._elevationReturnWaitTime;
  78845. },
  78846. /**
  78847. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  78848. */
  78849. set: function (time) {
  78850. this._elevationReturnWaitTime = time;
  78851. },
  78852. enumerable: true,
  78853. configurable: true
  78854. });
  78855. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  78856. /**
  78857. * Gets the flag that indicates if user zooming should stop animation.
  78858. */
  78859. get: function () {
  78860. return this._zoomStopsAnimation;
  78861. },
  78862. /**
  78863. * Sets the flag that indicates if user zooming should stop animation.
  78864. */
  78865. set: function (flag) {
  78866. this._zoomStopsAnimation = flag;
  78867. },
  78868. enumerable: true,
  78869. configurable: true
  78870. });
  78871. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  78872. /**
  78873. * Gets the transition time when framing the mesh, in milliseconds
  78874. */
  78875. get: function () {
  78876. return this._framingTime;
  78877. },
  78878. /**
  78879. * Sets the transition time when framing the mesh, in milliseconds
  78880. */
  78881. set: function (time) {
  78882. this._framingTime = time;
  78883. },
  78884. enumerable: true,
  78885. configurable: true
  78886. });
  78887. FramingBehavior.prototype.init = function () {
  78888. // Do notihng
  78889. };
  78890. FramingBehavior.prototype.attach = function (camera) {
  78891. var _this = this;
  78892. this._attachedCamera = camera;
  78893. var scene = this._attachedCamera.getScene();
  78894. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  78895. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  78896. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  78897. _this._isPointerDown = true;
  78898. return;
  78899. }
  78900. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  78901. _this._isPointerDown = false;
  78902. }
  78903. });
  78904. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  78905. if (mesh) {
  78906. _this.zoomOnMesh(mesh);
  78907. }
  78908. });
  78909. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  78910. // Stop the animation if there is user interaction and the animation should stop for this interaction
  78911. _this._applyUserInteraction();
  78912. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  78913. // back to the default position after a given timeout
  78914. _this._maintainCameraAboveGround();
  78915. });
  78916. };
  78917. FramingBehavior.prototype.detach = function () {
  78918. if (!this._attachedCamera) {
  78919. return;
  78920. }
  78921. var scene = this._attachedCamera.getScene();
  78922. if (this._onPrePointerObservableObserver) {
  78923. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  78924. }
  78925. if (this._onAfterCheckInputsObserver) {
  78926. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  78927. }
  78928. if (this._onMeshTargetChangedObserver) {
  78929. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  78930. }
  78931. this._attachedCamera = null;
  78932. };
  78933. /**
  78934. * Targets the given mesh and updates zoom level accordingly.
  78935. * @param mesh The mesh to target.
  78936. * @param radius Optional. If a cached radius position already exists, overrides default.
  78937. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78938. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78939. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78940. */
  78941. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  78942. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78943. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78944. mesh.computeWorldMatrix(true);
  78945. var boundingBox = mesh.getBoundingInfo().boundingBox;
  78946. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  78947. };
  78948. /**
  78949. * Targets the given mesh with its children and updates zoom level accordingly.
  78950. * @param mesh The mesh to target.
  78951. * @param radius Optional. If a cached radius position already exists, overrides default.
  78952. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78953. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78954. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78955. */
  78956. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  78957. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78958. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78959. mesh.computeWorldMatrix(true);
  78960. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  78961. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  78962. };
  78963. /**
  78964. * Targets the given meshes with their children and updates zoom level accordingly.
  78965. * @param meshes The mesh to target.
  78966. * @param radius Optional. If a cached radius position already exists, overrides default.
  78967. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78968. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78969. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78970. */
  78971. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  78972. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78973. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78974. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  78975. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  78976. for (var i = 0; i < meshes.length; i++) {
  78977. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  78978. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  78979. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  78980. }
  78981. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  78982. };
  78983. /**
  78984. * Targets the given mesh and updates zoom level accordingly.
  78985. * @param mesh The mesh to target.
  78986. * @param radius Optional. If a cached radius position already exists, overrides default.
  78987. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78988. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78989. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78990. */
  78991. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  78992. var _this = this;
  78993. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78994. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78995. var zoomTarget;
  78996. if (!this._attachedCamera) {
  78997. return;
  78998. }
  78999. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  79000. var bottom = minimumWorld.y;
  79001. var top = maximumWorld.y;
  79002. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  79003. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  79004. if (focusOnOriginXZ) {
  79005. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  79006. }
  79007. else {
  79008. var centerWorld = minimumWorld.add(radiusWorld);
  79009. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  79010. }
  79011. if (!this._vectorTransition) {
  79012. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  79013. }
  79014. this._betaIsAnimating = true;
  79015. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  79016. if (animatable) {
  79017. this._animatables.push(animatable);
  79018. }
  79019. // sets the radius and lower radius bounds
  79020. // Small delta ensures camera is not always at lower zoom limit.
  79021. var radius = 0;
  79022. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  79023. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  79024. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  79025. radius = position;
  79026. }
  79027. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  79028. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  79029. if (this._attachedCamera.lowerRadiusLimit === null) {
  79030. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  79031. }
  79032. }
  79033. // Set sensibilities
  79034. var extend = maximumWorld.subtract(minimumWorld).length();
  79035. this._attachedCamera.panningSensibility = 5000 / extend;
  79036. this._attachedCamera.wheelPrecision = 100 / radius;
  79037. // transition to new radius
  79038. if (!this._radiusTransition) {
  79039. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  79040. }
  79041. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  79042. if (onAnimationEnd) {
  79043. onAnimationEnd();
  79044. }
  79045. if (_this._attachedCamera) {
  79046. _this._attachedCamera.storeState();
  79047. }
  79048. });
  79049. if (animatable) {
  79050. this._animatables.push(animatable);
  79051. }
  79052. };
  79053. /**
  79054. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  79055. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  79056. * frustum width.
  79057. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  79058. * to fully enclose the mesh in the viewing frustum.
  79059. */
  79060. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  79061. var size = maximumWorld.subtract(minimumWorld);
  79062. var boxVectorGlobalDiagonal = size.length();
  79063. var frustumSlope = this._getFrustumSlope();
  79064. // Formula for setting distance
  79065. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  79066. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  79067. // Horizon distance
  79068. var radius = radiusWithoutFraming * this._radiusScale;
  79069. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  79070. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  79071. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  79072. var camera = this._attachedCamera;
  79073. if (!camera) {
  79074. return 0;
  79075. }
  79076. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  79077. // Don't exceed the requested limit
  79078. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  79079. }
  79080. // Don't exceed the upper radius limit
  79081. if (camera.upperRadiusLimit) {
  79082. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  79083. }
  79084. return distance;
  79085. };
  79086. /**
  79087. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  79088. * is automatically returned to its default position (expected to be above ground plane).
  79089. */
  79090. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  79091. var _this = this;
  79092. if (this._elevationReturnTime < 0) {
  79093. return;
  79094. }
  79095. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  79096. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  79097. var limitBeta = Math.PI * 0.5;
  79098. // Bring the camera back up if below the ground plane
  79099. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  79100. this._betaIsAnimating = true;
  79101. //Transition to new position
  79102. this.stopAllAnimations();
  79103. if (!this._betaTransition) {
  79104. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  79105. }
  79106. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  79107. _this._clearAnimationLocks();
  79108. _this.stopAllAnimations();
  79109. });
  79110. if (animatabe) {
  79111. this._animatables.push(animatabe);
  79112. }
  79113. }
  79114. };
  79115. /**
  79116. * Returns the frustum slope based on the canvas ratio and camera FOV
  79117. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  79118. */
  79119. FramingBehavior.prototype._getFrustumSlope = function () {
  79120. // Calculate the viewport ratio
  79121. // Aspect Ratio is Height/Width.
  79122. var camera = this._attachedCamera;
  79123. if (!camera) {
  79124. return BABYLON.Vector2.Zero();
  79125. }
  79126. var engine = camera.getScene().getEngine();
  79127. var aspectRatio = engine.getAspectRatio(camera);
  79128. // Camera FOV is the vertical field of view (top-bottom) in radians.
  79129. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  79130. var frustumSlopeY = Math.tan(camera.fov / 2);
  79131. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  79132. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  79133. // along the forward vector.
  79134. var frustumSlopeX = frustumSlopeY * aspectRatio;
  79135. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  79136. };
  79137. /**
  79138. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  79139. */
  79140. FramingBehavior.prototype._clearAnimationLocks = function () {
  79141. this._betaIsAnimating = false;
  79142. };
  79143. /**
  79144. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  79145. */
  79146. FramingBehavior.prototype._applyUserInteraction = function () {
  79147. if (this.isUserIsMoving) {
  79148. this._lastInteractionTime = BABYLON.Tools.Now;
  79149. this.stopAllAnimations();
  79150. this._clearAnimationLocks();
  79151. }
  79152. };
  79153. /**
  79154. * Stops and removes all animations that have been applied to the camera
  79155. */
  79156. FramingBehavior.prototype.stopAllAnimations = function () {
  79157. if (this._attachedCamera) {
  79158. this._attachedCamera.animations = [];
  79159. }
  79160. while (this._animatables.length) {
  79161. if (this._animatables[0]) {
  79162. this._animatables[0].onAnimationEnd = null;
  79163. this._animatables[0].stop();
  79164. }
  79165. this._animatables.shift();
  79166. }
  79167. };
  79168. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  79169. /**
  79170. * Gets a value indicating if the user is moving the camera
  79171. */
  79172. get: function () {
  79173. if (!this._attachedCamera) {
  79174. return false;
  79175. }
  79176. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  79177. this._attachedCamera.inertialBetaOffset !== 0 ||
  79178. this._attachedCamera.inertialRadiusOffset !== 0 ||
  79179. this._attachedCamera.inertialPanningX !== 0 ||
  79180. this._attachedCamera.inertialPanningY !== 0 ||
  79181. this._isPointerDown;
  79182. },
  79183. enumerable: true,
  79184. configurable: true
  79185. });
  79186. /**
  79187. * The easing function used by animations
  79188. */
  79189. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  79190. /**
  79191. * The easing mode used by animations
  79192. */
  79193. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  79194. // Statics
  79195. /**
  79196. * The camera can move all the way towards the mesh.
  79197. */
  79198. FramingBehavior.IgnoreBoundsSizeMode = 0;
  79199. /**
  79200. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  79201. */
  79202. FramingBehavior.FitFrustumSidesMode = 1;
  79203. return FramingBehavior;
  79204. }());
  79205. BABYLON.FramingBehavior = FramingBehavior;
  79206. })(BABYLON || (BABYLON = {}));
  79207. //# sourceMappingURL=babylon.framingBehavior.js.map
  79208. var BABYLON;
  79209. (function (BABYLON) {
  79210. /**
  79211. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  79212. */
  79213. var BouncingBehavior = /** @class */ (function () {
  79214. function BouncingBehavior() {
  79215. /**
  79216. * The duration of the animation, in milliseconds
  79217. */
  79218. this.transitionDuration = 450;
  79219. /**
  79220. * Length of the distance animated by the transition when lower radius is reached
  79221. */
  79222. this.lowerRadiusTransitionRange = 2;
  79223. /**
  79224. * Length of the distance animated by the transition when upper radius is reached
  79225. */
  79226. this.upperRadiusTransitionRange = -2;
  79227. this._autoTransitionRange = false;
  79228. // Animations
  79229. this._radiusIsAnimating = false;
  79230. this._radiusBounceTransition = null;
  79231. this._animatables = new Array();
  79232. }
  79233. Object.defineProperty(BouncingBehavior.prototype, "name", {
  79234. get: function () {
  79235. return "Bouncing";
  79236. },
  79237. enumerable: true,
  79238. configurable: true
  79239. });
  79240. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  79241. /**
  79242. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  79243. */
  79244. get: function () {
  79245. return this._autoTransitionRange;
  79246. },
  79247. /**
  79248. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  79249. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  79250. */
  79251. set: function (value) {
  79252. var _this = this;
  79253. if (this._autoTransitionRange === value) {
  79254. return;
  79255. }
  79256. this._autoTransitionRange = value;
  79257. var camera = this._attachedCamera;
  79258. if (!camera) {
  79259. return;
  79260. }
  79261. if (value) {
  79262. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  79263. if (!mesh) {
  79264. return;
  79265. }
  79266. mesh.computeWorldMatrix(true);
  79267. var diagonal = mesh.getBoundingInfo().diagonalLength;
  79268. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  79269. _this.upperRadiusTransitionRange = diagonal * 0.05;
  79270. });
  79271. }
  79272. else if (this._onMeshTargetChangedObserver) {
  79273. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  79274. }
  79275. },
  79276. enumerable: true,
  79277. configurable: true
  79278. });
  79279. BouncingBehavior.prototype.init = function () {
  79280. // Do notihng
  79281. };
  79282. BouncingBehavior.prototype.attach = function (camera) {
  79283. var _this = this;
  79284. this._attachedCamera = camera;
  79285. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  79286. if (!_this._attachedCamera) {
  79287. return;
  79288. }
  79289. // Add the bounce animation to the lower radius limit
  79290. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  79291. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  79292. }
  79293. // Add the bounce animation to the upper radius limit
  79294. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  79295. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  79296. }
  79297. });
  79298. };
  79299. BouncingBehavior.prototype.detach = function () {
  79300. if (!this._attachedCamera) {
  79301. return;
  79302. }
  79303. if (this._onAfterCheckInputsObserver) {
  79304. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  79305. }
  79306. if (this._onMeshTargetChangedObserver) {
  79307. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  79308. }
  79309. this._attachedCamera = null;
  79310. };
  79311. /**
  79312. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  79313. * @param radiusLimit The limit to check against.
  79314. * @return Bool to indicate if at limit.
  79315. */
  79316. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  79317. if (!this._attachedCamera) {
  79318. return false;
  79319. }
  79320. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  79321. return true;
  79322. }
  79323. return false;
  79324. };
  79325. /**
  79326. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  79327. * @param radiusDelta The delta by which to animate to. Can be negative.
  79328. */
  79329. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  79330. var _this = this;
  79331. if (!this._attachedCamera) {
  79332. return;
  79333. }
  79334. if (!this._radiusBounceTransition) {
  79335. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  79336. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  79337. }
  79338. // Prevent zoom until bounce has completed
  79339. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  79340. this._attachedCamera.wheelPrecision = Infinity;
  79341. this._attachedCamera.inertialRadiusOffset = 0;
  79342. // Animate to the radius limit
  79343. this.stopAllAnimations();
  79344. this._radiusIsAnimating = true;
  79345. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  79346. if (animatable) {
  79347. this._animatables.push(animatable);
  79348. }
  79349. };
  79350. /**
  79351. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  79352. */
  79353. BouncingBehavior.prototype._clearAnimationLocks = function () {
  79354. this._radiusIsAnimating = false;
  79355. if (this._attachedCamera) {
  79356. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  79357. }
  79358. };
  79359. /**
  79360. * Stops and removes all animations that have been applied to the camera
  79361. */
  79362. BouncingBehavior.prototype.stopAllAnimations = function () {
  79363. if (this._attachedCamera) {
  79364. this._attachedCamera.animations = [];
  79365. }
  79366. while (this._animatables.length) {
  79367. this._animatables[0].onAnimationEnd = null;
  79368. this._animatables[0].stop();
  79369. this._animatables.shift();
  79370. }
  79371. };
  79372. /**
  79373. * The easing function used by animations
  79374. */
  79375. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  79376. /**
  79377. * The easing mode used by animations
  79378. */
  79379. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  79380. return BouncingBehavior;
  79381. }());
  79382. BABYLON.BouncingBehavior = BouncingBehavior;
  79383. })(BABYLON || (BABYLON = {}));
  79384. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  79385. var BABYLON;
  79386. (function (BABYLON) {
  79387. var AutoRotationBehavior = /** @class */ (function () {
  79388. function AutoRotationBehavior() {
  79389. this._zoomStopsAnimation = false;
  79390. this._idleRotationSpeed = 0.05;
  79391. this._idleRotationWaitTime = 2000;
  79392. this._idleRotationSpinupTime = 2000;
  79393. this._isPointerDown = false;
  79394. this._lastFrameTime = null;
  79395. this._lastInteractionTime = -Infinity;
  79396. this._cameraRotationSpeed = 0;
  79397. this._lastFrameRadius = 0;
  79398. }
  79399. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  79400. get: function () {
  79401. return "AutoRotation";
  79402. },
  79403. enumerable: true,
  79404. configurable: true
  79405. });
  79406. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  79407. /**
  79408. * Gets the flag that indicates if user zooming should stop animation.
  79409. */
  79410. get: function () {
  79411. return this._zoomStopsAnimation;
  79412. },
  79413. /**
  79414. * Sets the flag that indicates if user zooming should stop animation.
  79415. */
  79416. set: function (flag) {
  79417. this._zoomStopsAnimation = flag;
  79418. },
  79419. enumerable: true,
  79420. configurable: true
  79421. });
  79422. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  79423. /**
  79424. * Gets the default speed at which the camera rotates around the model.
  79425. */
  79426. get: function () {
  79427. return this._idleRotationSpeed;
  79428. },
  79429. /**
  79430. * Sets the default speed at which the camera rotates around the model.
  79431. */
  79432. set: function (speed) {
  79433. this._idleRotationSpeed = speed;
  79434. },
  79435. enumerable: true,
  79436. configurable: true
  79437. });
  79438. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  79439. /**
  79440. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  79441. */
  79442. get: function () {
  79443. return this._idleRotationWaitTime;
  79444. },
  79445. /**
  79446. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  79447. */
  79448. set: function (time) {
  79449. this._idleRotationWaitTime = time;
  79450. },
  79451. enumerable: true,
  79452. configurable: true
  79453. });
  79454. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  79455. /**
  79456. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  79457. */
  79458. get: function () {
  79459. return this._idleRotationSpinupTime;
  79460. },
  79461. /**
  79462. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  79463. */
  79464. set: function (time) {
  79465. this._idleRotationSpinupTime = time;
  79466. },
  79467. enumerable: true,
  79468. configurable: true
  79469. });
  79470. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  79471. /**
  79472. * Gets a value indicating if the camera is currently rotating because of this behavior
  79473. */
  79474. get: function () {
  79475. return Math.abs(this._cameraRotationSpeed) > 0;
  79476. },
  79477. enumerable: true,
  79478. configurable: true
  79479. });
  79480. AutoRotationBehavior.prototype.init = function () {
  79481. // Do notihng
  79482. };
  79483. AutoRotationBehavior.prototype.attach = function (camera) {
  79484. var _this = this;
  79485. this._attachedCamera = camera;
  79486. var scene = this._attachedCamera.getScene();
  79487. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  79488. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  79489. _this._isPointerDown = true;
  79490. return;
  79491. }
  79492. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  79493. _this._isPointerDown = false;
  79494. }
  79495. });
  79496. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  79497. var now = BABYLON.Tools.Now;
  79498. var dt = 0;
  79499. if (_this._lastFrameTime != null) {
  79500. dt = now - _this._lastFrameTime;
  79501. }
  79502. _this._lastFrameTime = now;
  79503. // Stop the animation if there is user interaction and the animation should stop for this interaction
  79504. _this._applyUserInteraction();
  79505. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  79506. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  79507. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  79508. // Step camera rotation by rotation speed
  79509. if (_this._attachedCamera) {
  79510. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  79511. }
  79512. });
  79513. };
  79514. AutoRotationBehavior.prototype.detach = function () {
  79515. if (!this._attachedCamera) {
  79516. return;
  79517. }
  79518. var scene = this._attachedCamera.getScene();
  79519. if (this._onPrePointerObservableObserver) {
  79520. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  79521. }
  79522. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  79523. this._attachedCamera = null;
  79524. };
  79525. /**
  79526. * Returns true if user is scrolling.
  79527. * @return true if user is scrolling.
  79528. */
  79529. AutoRotationBehavior.prototype._userIsZooming = function () {
  79530. if (!this._attachedCamera) {
  79531. return false;
  79532. }
  79533. return this._attachedCamera.inertialRadiusOffset !== 0;
  79534. };
  79535. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  79536. if (!this._attachedCamera) {
  79537. return false;
  79538. }
  79539. var zoomHasHitLimit = false;
  79540. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  79541. zoomHasHitLimit = true;
  79542. }
  79543. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  79544. this._lastFrameRadius = this._attachedCamera.radius;
  79545. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  79546. };
  79547. /**
  79548. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  79549. */
  79550. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  79551. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  79552. this._lastInteractionTime = BABYLON.Tools.Now;
  79553. }
  79554. };
  79555. // Tools
  79556. AutoRotationBehavior.prototype._userIsMoving = function () {
  79557. if (!this._attachedCamera) {
  79558. return false;
  79559. }
  79560. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  79561. this._attachedCamera.inertialBetaOffset !== 0 ||
  79562. this._attachedCamera.inertialRadiusOffset !== 0 ||
  79563. this._attachedCamera.inertialPanningX !== 0 ||
  79564. this._attachedCamera.inertialPanningY !== 0 ||
  79565. this._isPointerDown;
  79566. };
  79567. return AutoRotationBehavior;
  79568. }());
  79569. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  79570. })(BABYLON || (BABYLON = {}));
  79571. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  79572. var BABYLON;
  79573. (function (BABYLON) {
  79574. /**
  79575. * This class can be used to get instrumentation data from a Babylon engine
  79576. */
  79577. var EngineInstrumentation = /** @class */ (function () {
  79578. function EngineInstrumentation(engine) {
  79579. this.engine = engine;
  79580. this._captureGPUFrameTime = false;
  79581. this._gpuFrameTime = new BABYLON.PerfCounter();
  79582. this._captureShaderCompilationTime = false;
  79583. this._shaderCompilationTime = new BABYLON.PerfCounter();
  79584. // Observers
  79585. this._onBeginFrameObserver = null;
  79586. this._onEndFrameObserver = null;
  79587. this._onBeforeShaderCompilationObserver = null;
  79588. this._onAfterShaderCompilationObserver = null;
  79589. }
  79590. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  79591. // Properties
  79592. /**
  79593. * Gets the perf counter used for GPU frame time
  79594. */
  79595. get: function () {
  79596. return this._gpuFrameTime;
  79597. },
  79598. enumerable: true,
  79599. configurable: true
  79600. });
  79601. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  79602. /**
  79603. * Gets the GPU frame time capture status
  79604. */
  79605. get: function () {
  79606. return this._captureGPUFrameTime;
  79607. },
  79608. /**
  79609. * Enable or disable the GPU frame time capture
  79610. */
  79611. set: function (value) {
  79612. var _this = this;
  79613. if (value === this._captureGPUFrameTime) {
  79614. return;
  79615. }
  79616. this._captureGPUFrameTime = value;
  79617. if (value) {
  79618. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  79619. if (!_this._gpuFrameTimeToken) {
  79620. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  79621. }
  79622. });
  79623. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  79624. if (!_this._gpuFrameTimeToken) {
  79625. return;
  79626. }
  79627. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  79628. if (time > -1) {
  79629. _this._gpuFrameTimeToken = null;
  79630. _this._gpuFrameTime.fetchNewFrame();
  79631. _this._gpuFrameTime.addCount(time, true);
  79632. }
  79633. });
  79634. }
  79635. else {
  79636. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  79637. this._onBeginFrameObserver = null;
  79638. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  79639. this._onEndFrameObserver = null;
  79640. }
  79641. },
  79642. enumerable: true,
  79643. configurable: true
  79644. });
  79645. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  79646. /**
  79647. * Gets the perf counter used for shader compilation time
  79648. */
  79649. get: function () {
  79650. return this._shaderCompilationTime;
  79651. },
  79652. enumerable: true,
  79653. configurable: true
  79654. });
  79655. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  79656. /**
  79657. * Gets the shader compilation time capture status
  79658. */
  79659. get: function () {
  79660. return this._captureShaderCompilationTime;
  79661. },
  79662. /**
  79663. * Enable or disable the shader compilation time capture
  79664. */
  79665. set: function (value) {
  79666. var _this = this;
  79667. if (value === this._captureShaderCompilationTime) {
  79668. return;
  79669. }
  79670. this._captureShaderCompilationTime = value;
  79671. if (value) {
  79672. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  79673. _this._shaderCompilationTime.fetchNewFrame();
  79674. _this._shaderCompilationTime.beginMonitoring();
  79675. });
  79676. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  79677. _this._shaderCompilationTime.endMonitoring();
  79678. });
  79679. }
  79680. else {
  79681. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  79682. this._onBeforeShaderCompilationObserver = null;
  79683. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  79684. this._onAfterShaderCompilationObserver = null;
  79685. }
  79686. },
  79687. enumerable: true,
  79688. configurable: true
  79689. });
  79690. EngineInstrumentation.prototype.dispose = function () {
  79691. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  79692. this._onBeginFrameObserver = null;
  79693. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  79694. this._onEndFrameObserver = null;
  79695. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  79696. this._onBeforeShaderCompilationObserver = null;
  79697. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  79698. this._onAfterShaderCompilationObserver = null;
  79699. this.engine = null;
  79700. };
  79701. return EngineInstrumentation;
  79702. }());
  79703. BABYLON.EngineInstrumentation = EngineInstrumentation;
  79704. })(BABYLON || (BABYLON = {}));
  79705. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  79706. var BABYLON;
  79707. (function (BABYLON) {
  79708. /**
  79709. * This class can be used to get instrumentation data from a Babylon engine
  79710. */
  79711. var SceneInstrumentation = /** @class */ (function () {
  79712. function SceneInstrumentation(scene) {
  79713. var _this = this;
  79714. this.scene = scene;
  79715. this._captureActiveMeshesEvaluationTime = false;
  79716. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  79717. this._captureRenderTargetsRenderTime = false;
  79718. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  79719. this._captureFrameTime = false;
  79720. this._frameTime = new BABYLON.PerfCounter();
  79721. this._captureRenderTime = false;
  79722. this._renderTime = new BABYLON.PerfCounter();
  79723. this._captureInterFrameTime = false;
  79724. this._interFrameTime = new BABYLON.PerfCounter();
  79725. this._captureParticlesRenderTime = false;
  79726. this._particlesRenderTime = new BABYLON.PerfCounter();
  79727. this._captureSpritesRenderTime = false;
  79728. this._spritesRenderTime = new BABYLON.PerfCounter();
  79729. this._capturePhysicsTime = false;
  79730. this._physicsTime = new BABYLON.PerfCounter();
  79731. this._captureAnimationsTime = false;
  79732. this._animationsTime = new BABYLON.PerfCounter();
  79733. // Observers
  79734. this._onBeforeActiveMeshesEvaluationObserver = null;
  79735. this._onAfterActiveMeshesEvaluationObserver = null;
  79736. this._onBeforeRenderTargetsRenderObserver = null;
  79737. this._onAfterRenderTargetsRenderObserver = null;
  79738. this._onAfterRenderObserver = null;
  79739. this._onBeforeDrawPhaseObserver = null;
  79740. this._onAfterDrawPhaseObserver = null;
  79741. this._onBeforeAnimationsObserver = null;
  79742. this._onBeforeParticlesRenderingObserver = null;
  79743. this._onAfterParticlesRenderingObserver = null;
  79744. this._onBeforeSpritesRenderingObserver = null;
  79745. this._onAfterSpritesRenderingObserver = null;
  79746. this._onBeforePhysicsObserver = null;
  79747. this._onAfterPhysicsObserver = null;
  79748. this._onAfterAnimationsObserver = null;
  79749. // Before render
  79750. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  79751. if (_this._captureActiveMeshesEvaluationTime) {
  79752. _this._activeMeshesEvaluationTime.fetchNewFrame();
  79753. }
  79754. if (_this._captureRenderTargetsRenderTime) {
  79755. _this._renderTargetsRenderTime.fetchNewFrame();
  79756. }
  79757. if (_this._captureFrameTime) {
  79758. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  79759. _this._frameTime.beginMonitoring();
  79760. }
  79761. if (_this._captureInterFrameTime) {
  79762. _this._interFrameTime.endMonitoring();
  79763. }
  79764. if (_this._captureParticlesRenderTime) {
  79765. _this._particlesRenderTime.fetchNewFrame();
  79766. }
  79767. if (_this._captureSpritesRenderTime) {
  79768. _this._spritesRenderTime.fetchNewFrame();
  79769. }
  79770. if (_this._captureAnimationsTime) {
  79771. _this._animationsTime.beginMonitoring();
  79772. }
  79773. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  79774. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  79775. });
  79776. // After render
  79777. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  79778. if (_this._captureFrameTime) {
  79779. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  79780. _this._frameTime.endMonitoring();
  79781. }
  79782. if (_this._captureRenderTime) {
  79783. _this._renderTime.endMonitoring(false);
  79784. }
  79785. if (_this._captureInterFrameTime) {
  79786. _this._interFrameTime.beginMonitoring();
  79787. }
  79788. });
  79789. }
  79790. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  79791. // Properties
  79792. /**
  79793. * Gets the perf counter used for active meshes evaluation time
  79794. */
  79795. get: function () {
  79796. return this._activeMeshesEvaluationTime;
  79797. },
  79798. enumerable: true,
  79799. configurable: true
  79800. });
  79801. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  79802. /**
  79803. * Gets the active meshes evaluation time capture status
  79804. */
  79805. get: function () {
  79806. return this._captureActiveMeshesEvaluationTime;
  79807. },
  79808. /**
  79809. * Enable or disable the active meshes evaluation time capture
  79810. */
  79811. set: function (value) {
  79812. var _this = this;
  79813. if (value === this._captureActiveMeshesEvaluationTime) {
  79814. return;
  79815. }
  79816. this._captureActiveMeshesEvaluationTime = value;
  79817. if (value) {
  79818. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  79819. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  79820. _this._activeMeshesEvaluationTime.beginMonitoring();
  79821. });
  79822. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  79823. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  79824. _this._activeMeshesEvaluationTime.endMonitoring();
  79825. });
  79826. }
  79827. else {
  79828. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  79829. this._onBeforeActiveMeshesEvaluationObserver = null;
  79830. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  79831. this._onAfterActiveMeshesEvaluationObserver = null;
  79832. }
  79833. },
  79834. enumerable: true,
  79835. configurable: true
  79836. });
  79837. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  79838. /**
  79839. * Gets the perf counter used for render targets render time
  79840. */
  79841. get: function () {
  79842. return this._renderTargetsRenderTime;
  79843. },
  79844. enumerable: true,
  79845. configurable: true
  79846. });
  79847. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  79848. /**
  79849. * Gets the render targets render time capture status
  79850. */
  79851. get: function () {
  79852. return this._captureRenderTargetsRenderTime;
  79853. },
  79854. /**
  79855. * Enable or disable the render targets render time capture
  79856. */
  79857. set: function (value) {
  79858. var _this = this;
  79859. if (value === this._captureRenderTargetsRenderTime) {
  79860. return;
  79861. }
  79862. this._captureRenderTargetsRenderTime = value;
  79863. if (value) {
  79864. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  79865. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  79866. _this._renderTargetsRenderTime.beginMonitoring();
  79867. });
  79868. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  79869. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  79870. _this._renderTargetsRenderTime.endMonitoring(false);
  79871. });
  79872. }
  79873. else {
  79874. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  79875. this._onBeforeRenderTargetsRenderObserver = null;
  79876. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  79877. this._onAfterRenderTargetsRenderObserver = null;
  79878. }
  79879. },
  79880. enumerable: true,
  79881. configurable: true
  79882. });
  79883. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  79884. /**
  79885. * Gets the perf counter used for particles render time
  79886. */
  79887. get: function () {
  79888. return this._particlesRenderTime;
  79889. },
  79890. enumerable: true,
  79891. configurable: true
  79892. });
  79893. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  79894. /**
  79895. * Gets the particles render time capture status
  79896. */
  79897. get: function () {
  79898. return this._captureParticlesRenderTime;
  79899. },
  79900. /**
  79901. * Enable or disable the particles render time capture
  79902. */
  79903. set: function (value) {
  79904. var _this = this;
  79905. if (value === this._captureParticlesRenderTime) {
  79906. return;
  79907. }
  79908. this._captureParticlesRenderTime = value;
  79909. if (value) {
  79910. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  79911. BABYLON.Tools.StartPerformanceCounter("Particles");
  79912. _this._particlesRenderTime.beginMonitoring();
  79913. });
  79914. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  79915. BABYLON.Tools.EndPerformanceCounter("Particles");
  79916. _this._particlesRenderTime.endMonitoring(false);
  79917. });
  79918. }
  79919. else {
  79920. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  79921. this._onBeforeParticlesRenderingObserver = null;
  79922. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  79923. this._onAfterParticlesRenderingObserver = null;
  79924. }
  79925. },
  79926. enumerable: true,
  79927. configurable: true
  79928. });
  79929. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  79930. /**
  79931. * Gets the perf counter used for sprites render time
  79932. */
  79933. get: function () {
  79934. return this._spritesRenderTime;
  79935. },
  79936. enumerable: true,
  79937. configurable: true
  79938. });
  79939. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  79940. /**
  79941. * Gets the sprites render time capture status
  79942. */
  79943. get: function () {
  79944. return this._captureSpritesRenderTime;
  79945. },
  79946. /**
  79947. * Enable or disable the sprites render time capture
  79948. */
  79949. set: function (value) {
  79950. var _this = this;
  79951. if (value === this._captureSpritesRenderTime) {
  79952. return;
  79953. }
  79954. this._captureSpritesRenderTime = value;
  79955. if (value) {
  79956. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  79957. BABYLON.Tools.StartPerformanceCounter("Sprites");
  79958. _this._spritesRenderTime.beginMonitoring();
  79959. });
  79960. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  79961. BABYLON.Tools.EndPerformanceCounter("Sprites");
  79962. _this._spritesRenderTime.endMonitoring(false);
  79963. });
  79964. }
  79965. else {
  79966. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  79967. this._onBeforeSpritesRenderingObserver = null;
  79968. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  79969. this._onAfterSpritesRenderingObserver = null;
  79970. }
  79971. },
  79972. enumerable: true,
  79973. configurable: true
  79974. });
  79975. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  79976. /**
  79977. * Gets the perf counter used for physics time
  79978. */
  79979. get: function () {
  79980. return this._physicsTime;
  79981. },
  79982. enumerable: true,
  79983. configurable: true
  79984. });
  79985. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  79986. /**
  79987. * Gets the physics time capture status
  79988. */
  79989. get: function () {
  79990. return this._capturePhysicsTime;
  79991. },
  79992. /**
  79993. * Enable or disable the physics time capture
  79994. */
  79995. set: function (value) {
  79996. var _this = this;
  79997. if (value === this._capturePhysicsTime) {
  79998. return;
  79999. }
  80000. this._capturePhysicsTime = value;
  80001. if (value) {
  80002. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  80003. BABYLON.Tools.StartPerformanceCounter("Physics");
  80004. _this._physicsTime.beginMonitoring();
  80005. });
  80006. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  80007. BABYLON.Tools.EndPerformanceCounter("Physics");
  80008. _this._physicsTime.endMonitoring();
  80009. });
  80010. }
  80011. else {
  80012. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  80013. this._onBeforePhysicsObserver = null;
  80014. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  80015. this._onAfterPhysicsObserver = null;
  80016. }
  80017. },
  80018. enumerable: true,
  80019. configurable: true
  80020. });
  80021. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  80022. /**
  80023. * Gets the perf counter used for animations time
  80024. */
  80025. get: function () {
  80026. return this._animationsTime;
  80027. },
  80028. enumerable: true,
  80029. configurable: true
  80030. });
  80031. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  80032. /**
  80033. * Gets the animations time capture status
  80034. */
  80035. get: function () {
  80036. return this._captureAnimationsTime;
  80037. },
  80038. /**
  80039. * Enable or disable the animations time capture
  80040. */
  80041. set: function (value) {
  80042. var _this = this;
  80043. if (value === this._captureAnimationsTime) {
  80044. return;
  80045. }
  80046. this._captureAnimationsTime = value;
  80047. if (value) {
  80048. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  80049. _this._animationsTime.endMonitoring();
  80050. });
  80051. }
  80052. else {
  80053. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  80054. this._onAfterAnimationsObserver = null;
  80055. }
  80056. },
  80057. enumerable: true,
  80058. configurable: true
  80059. });
  80060. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  80061. /**
  80062. * Gets the perf counter used for frame time capture
  80063. */
  80064. get: function () {
  80065. return this._frameTime;
  80066. },
  80067. enumerable: true,
  80068. configurable: true
  80069. });
  80070. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  80071. /**
  80072. * Gets the frame time capture status
  80073. */
  80074. get: function () {
  80075. return this._captureFrameTime;
  80076. },
  80077. /**
  80078. * Enable or disable the frame time capture
  80079. */
  80080. set: function (value) {
  80081. this._captureFrameTime = value;
  80082. },
  80083. enumerable: true,
  80084. configurable: true
  80085. });
  80086. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  80087. /**
  80088. * Gets the perf counter used for inter-frames time capture
  80089. */
  80090. get: function () {
  80091. return this._interFrameTime;
  80092. },
  80093. enumerable: true,
  80094. configurable: true
  80095. });
  80096. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  80097. /**
  80098. * Gets the inter-frames time capture status
  80099. */
  80100. get: function () {
  80101. return this._captureInterFrameTime;
  80102. },
  80103. /**
  80104. * Enable or disable the inter-frames time capture
  80105. */
  80106. set: function (value) {
  80107. this._captureInterFrameTime = value;
  80108. },
  80109. enumerable: true,
  80110. configurable: true
  80111. });
  80112. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  80113. /**
  80114. * Gets the perf counter used for render time capture
  80115. */
  80116. get: function () {
  80117. return this._renderTime;
  80118. },
  80119. enumerable: true,
  80120. configurable: true
  80121. });
  80122. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  80123. /**
  80124. * Gets the render time capture status
  80125. */
  80126. get: function () {
  80127. return this._captureRenderTime;
  80128. },
  80129. /**
  80130. * Enable or disable the render time capture
  80131. */
  80132. set: function (value) {
  80133. var _this = this;
  80134. if (value === this._captureRenderTime) {
  80135. return;
  80136. }
  80137. this._captureRenderTime = value;
  80138. if (value) {
  80139. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  80140. _this._renderTime.beginMonitoring();
  80141. BABYLON.Tools.StartPerformanceCounter("Main render");
  80142. });
  80143. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  80144. _this._renderTime.endMonitoring(false);
  80145. BABYLON.Tools.EndPerformanceCounter("Main render");
  80146. });
  80147. }
  80148. else {
  80149. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  80150. this._onBeforeDrawPhaseObserver = null;
  80151. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  80152. this._onAfterDrawPhaseObserver = null;
  80153. }
  80154. },
  80155. enumerable: true,
  80156. configurable: true
  80157. });
  80158. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  80159. /**
  80160. * Gets the perf counter used for draw calls
  80161. */
  80162. get: function () {
  80163. return this.scene.getEngine()._drawCalls;
  80164. },
  80165. enumerable: true,
  80166. configurable: true
  80167. });
  80168. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  80169. /**
  80170. * Gets the perf counter used for texture collisions
  80171. */
  80172. get: function () {
  80173. return this.scene.getEngine()._textureCollisions;
  80174. },
  80175. enumerable: true,
  80176. configurable: true
  80177. });
  80178. SceneInstrumentation.prototype.dispose = function () {
  80179. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  80180. this._onAfterRenderObserver = null;
  80181. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  80182. this._onBeforeActiveMeshesEvaluationObserver = null;
  80183. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  80184. this._onAfterActiveMeshesEvaluationObserver = null;
  80185. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  80186. this._onBeforeRenderTargetsRenderObserver = null;
  80187. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  80188. this._onAfterRenderTargetsRenderObserver = null;
  80189. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  80190. this._onBeforeAnimationsObserver = null;
  80191. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  80192. this._onBeforeParticlesRenderingObserver = null;
  80193. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  80194. this._onAfterParticlesRenderingObserver = null;
  80195. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  80196. this._onBeforeSpritesRenderingObserver = null;
  80197. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  80198. this._onAfterSpritesRenderingObserver = null;
  80199. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  80200. this._onBeforeDrawPhaseObserver = null;
  80201. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  80202. this._onAfterDrawPhaseObserver = null;
  80203. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  80204. this._onBeforePhysicsObserver = null;
  80205. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  80206. this._onAfterPhysicsObserver = null;
  80207. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  80208. this._onAfterAnimationsObserver = null;
  80209. this.scene = null;
  80210. };
  80211. return SceneInstrumentation;
  80212. }());
  80213. BABYLON.SceneInstrumentation = SceneInstrumentation;
  80214. })(BABYLON || (BABYLON = {}));
  80215. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  80216. var BABYLON;
  80217. (function (BABYLON) {
  80218. var _TimeToken = /** @class */ (function () {
  80219. function _TimeToken() {
  80220. this._timeElapsedQueryEnded = false;
  80221. }
  80222. return _TimeToken;
  80223. }());
  80224. BABYLON._TimeToken = _TimeToken;
  80225. })(BABYLON || (BABYLON = {}));
  80226. //# sourceMappingURL=babylon.timeToken.js.map
  80227. var BABYLON;
  80228. (function (BABYLON) {
  80229. /**
  80230. * Background material defines definition.
  80231. */
  80232. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  80233. __extends(BackgroundMaterialDefines, _super);
  80234. /**
  80235. * Constructor of the defines.
  80236. */
  80237. function BackgroundMaterialDefines() {
  80238. var _this = _super.call(this) || this;
  80239. /**
  80240. * True if the diffuse texture is in use.
  80241. */
  80242. _this.DIFFUSE = false;
  80243. /**
  80244. * The direct UV channel to use.
  80245. */
  80246. _this.DIFFUSEDIRECTUV = 0;
  80247. /**
  80248. * True if the diffuse texture is in gamma space.
  80249. */
  80250. _this.GAMMADIFFUSE = false;
  80251. /**
  80252. * True if the diffuse texture has opacity in the alpha channel.
  80253. */
  80254. _this.DIFFUSEHASALPHA = false;
  80255. /**
  80256. * True if you want the material to fade to transparent at grazing angle.
  80257. */
  80258. _this.OPACITYFRESNEL = false;
  80259. /**
  80260. * True if an extra blur needs to be added in the reflection.
  80261. */
  80262. _this.REFLECTIONBLUR = false;
  80263. /**
  80264. * True if you want the material to fade to reflection at grazing angle.
  80265. */
  80266. _this.REFLECTIONFRESNEL = false;
  80267. /**
  80268. * True if you want the material to falloff as far as you move away from the scene center.
  80269. */
  80270. _this.REFLECTIONFALLOFF = false;
  80271. /**
  80272. * False if the current Webgl implementation does not support the texture lod extension.
  80273. */
  80274. _this.TEXTURELODSUPPORT = false;
  80275. /**
  80276. * True to ensure the data are premultiplied.
  80277. */
  80278. _this.PREMULTIPLYALPHA = false;
  80279. /**
  80280. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  80281. */
  80282. _this.USERGBCOLOR = false;
  80283. /**
  80284. * True to add noise in order to reduce the banding effect.
  80285. */
  80286. _this.NOISE = false;
  80287. // Image Processing Configuration.
  80288. _this.IMAGEPROCESSING = false;
  80289. _this.VIGNETTE = false;
  80290. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  80291. _this.VIGNETTEBLENDMODEOPAQUE = false;
  80292. _this.TONEMAPPING = false;
  80293. _this.CONTRAST = false;
  80294. _this.COLORCURVES = false;
  80295. _this.COLORGRADING = false;
  80296. _this.COLORGRADING3D = false;
  80297. _this.SAMPLER3DGREENDEPTH = false;
  80298. _this.SAMPLER3DBGRMAP = false;
  80299. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  80300. _this.EXPOSURE = false;
  80301. // Reflection.
  80302. _this.REFLECTION = false;
  80303. _this.REFLECTIONMAP_3D = false;
  80304. _this.REFLECTIONMAP_SPHERICAL = false;
  80305. _this.REFLECTIONMAP_PLANAR = false;
  80306. _this.REFLECTIONMAP_CUBIC = false;
  80307. _this.REFLECTIONMAP_PROJECTION = false;
  80308. _this.REFLECTIONMAP_SKYBOX = false;
  80309. _this.REFLECTIONMAP_EXPLICIT = false;
  80310. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  80311. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  80312. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  80313. _this.INVERTCUBICMAP = false;
  80314. _this.REFLECTIONMAP_OPPOSITEZ = false;
  80315. _this.LODINREFLECTIONALPHA = false;
  80316. _this.GAMMAREFLECTION = false;
  80317. // Default BJS.
  80318. _this.MAINUV1 = false;
  80319. _this.MAINUV2 = false;
  80320. _this.UV1 = false;
  80321. _this.UV2 = false;
  80322. _this.CLIPPLANE = false;
  80323. _this.POINTSIZE = false;
  80324. _this.FOG = false;
  80325. _this.NORMAL = false;
  80326. _this.NUM_BONE_INFLUENCERS = 0;
  80327. _this.BonesPerMesh = 0;
  80328. _this.INSTANCES = false;
  80329. _this.SHADOWFLOAT = false;
  80330. _this.rebuild();
  80331. return _this;
  80332. }
  80333. return BackgroundMaterialDefines;
  80334. }(BABYLON.MaterialDefines));
  80335. /**
  80336. * Background material used to create an efficient environement around your scene.
  80337. */
  80338. var BackgroundMaterial = /** @class */ (function (_super) {
  80339. __extends(BackgroundMaterial, _super);
  80340. /**
  80341. * constructor
  80342. * @param name The name of the material
  80343. * @param scene The scene to add the material to
  80344. */
  80345. function BackgroundMaterial(name, scene) {
  80346. var _this = _super.call(this, name, scene) || this;
  80347. _this.primaryColor = BABYLON.Color3.White();
  80348. _this.primaryLevel = 1;
  80349. _this.secondaryColor = BABYLON.Color3.Gray();
  80350. _this.secondaryLevel = 1;
  80351. _this.tertiaryColor = BABYLON.Color3.Black();
  80352. _this.tertiaryLevel = 1;
  80353. _this.reflectionTexture = null;
  80354. _this.reflectionBlur = 0;
  80355. _this.diffuseTexture = null;
  80356. /**
  80357. * Specify the list of lights casting shadow on the material.
  80358. * All scene shadow lights will be included if null.
  80359. */
  80360. _this._shadowLights = null;
  80361. _this.shadowLights = null;
  80362. _this.shadowBlurScale = 1;
  80363. _this.shadowLevel = 0;
  80364. _this.sceneCenter = BABYLON.Vector3.Zero();
  80365. _this.opacityFresnel = true;
  80366. _this.reflectionFresnel = false;
  80367. _this.reflectionFalloffDistance = 0.0;
  80368. _this.reflectionAmount = 1.0;
  80369. _this.reflectionReflectance0 = 0.05;
  80370. _this.reflectionReflectance90 = 0.5;
  80371. _this.useRGBColor = true;
  80372. _this.enableNoise = false;
  80373. /**
  80374. * Number of Simultaneous lights allowed on the material.
  80375. */
  80376. _this._maxSimultaneousLights = 4;
  80377. _this.maxSimultaneousLights = 4;
  80378. /**
  80379. * Keep track of the image processing observer to allow dispose and replace.
  80380. */
  80381. _this._imageProcessingObserver = null;
  80382. // Temp values kept as cache in the material.
  80383. _this._renderTargets = new BABYLON.SmartArray(16);
  80384. _this._reflectionControls = BABYLON.Vector4.Zero();
  80385. // Setup the default processing configuration to the scene.
  80386. _this._attachImageProcessingConfiguration(null);
  80387. _this.getRenderTargetTextures = function () {
  80388. _this._renderTargets.reset();
  80389. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  80390. _this._renderTargets.push(_this._diffuseTexture);
  80391. }
  80392. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  80393. _this._renderTargets.push(_this._reflectionTexture);
  80394. }
  80395. return _this._renderTargets;
  80396. };
  80397. return _this;
  80398. }
  80399. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  80400. /**
  80401. * Sets the reflection reflectance fresnel values according to the default standard
  80402. * empirically know to work well :-)
  80403. */
  80404. set: function (value) {
  80405. var reflectionWeight = value;
  80406. if (reflectionWeight < 0.5) {
  80407. reflectionWeight = reflectionWeight * 2.0;
  80408. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  80409. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  80410. }
  80411. else {
  80412. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  80413. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  80414. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  80415. }
  80416. },
  80417. enumerable: true,
  80418. configurable: true
  80419. });
  80420. /**
  80421. * Attaches a new image processing configuration to the PBR Material.
  80422. * @param configuration (if null the scene configuration will be use)
  80423. */
  80424. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  80425. var _this = this;
  80426. if (configuration === this._imageProcessingConfiguration) {
  80427. return;
  80428. }
  80429. // Detaches observer.
  80430. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80431. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80432. }
  80433. // Pick the scene configuration if needed.
  80434. if (!configuration) {
  80435. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  80436. }
  80437. else {
  80438. this._imageProcessingConfiguration = configuration;
  80439. }
  80440. // Attaches observer.
  80441. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  80442. _this._markAllSubMeshesAsImageProcessingDirty();
  80443. });
  80444. };
  80445. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  80446. /**
  80447. * Gets the image processing configuration used either in this material.
  80448. */
  80449. get: function () {
  80450. return this._imageProcessingConfiguration;
  80451. },
  80452. /**
  80453. * Sets the Default image processing configuration used either in the this material.
  80454. *
  80455. * If sets to null, the scene one is in use.
  80456. */
  80457. set: function (value) {
  80458. this._attachImageProcessingConfiguration(value);
  80459. // Ensure the effect will be rebuilt.
  80460. this._markAllSubMeshesAsTexturesDirty();
  80461. },
  80462. enumerable: true,
  80463. configurable: true
  80464. });
  80465. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  80466. /**
  80467. * Gets wether the color curves effect is enabled.
  80468. */
  80469. get: function () {
  80470. return this.imageProcessingConfiguration.colorCurvesEnabled;
  80471. },
  80472. /**
  80473. * Sets wether the color curves effect is enabled.
  80474. */
  80475. set: function (value) {
  80476. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  80477. },
  80478. enumerable: true,
  80479. configurable: true
  80480. });
  80481. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  80482. /**
  80483. * Gets wether the color grading effect is enabled.
  80484. */
  80485. get: function () {
  80486. return this.imageProcessingConfiguration.colorGradingEnabled;
  80487. },
  80488. /**
  80489. * Gets wether the color grading effect is enabled.
  80490. */
  80491. set: function (value) {
  80492. this.imageProcessingConfiguration.colorGradingEnabled = value;
  80493. },
  80494. enumerable: true,
  80495. configurable: true
  80496. });
  80497. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  80498. /**
  80499. * Gets wether tonemapping is enabled or not.
  80500. */
  80501. get: function () {
  80502. return this._imageProcessingConfiguration.toneMappingEnabled;
  80503. },
  80504. /**
  80505. * Sets wether tonemapping is enabled or not
  80506. */
  80507. set: function (value) {
  80508. this._imageProcessingConfiguration.toneMappingEnabled = value;
  80509. },
  80510. enumerable: true,
  80511. configurable: true
  80512. });
  80513. ;
  80514. ;
  80515. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  80516. /**
  80517. * The camera exposure used on this material.
  80518. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  80519. * This corresponds to a photographic exposure.
  80520. */
  80521. get: function () {
  80522. return this._imageProcessingConfiguration.exposure;
  80523. },
  80524. /**
  80525. * The camera exposure used on this material.
  80526. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  80527. * This corresponds to a photographic exposure.
  80528. */
  80529. set: function (value) {
  80530. this._imageProcessingConfiguration.exposure = value;
  80531. },
  80532. enumerable: true,
  80533. configurable: true
  80534. });
  80535. ;
  80536. ;
  80537. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  80538. /**
  80539. * Gets The camera contrast used on this material.
  80540. */
  80541. get: function () {
  80542. return this._imageProcessingConfiguration.contrast;
  80543. },
  80544. /**
  80545. * Sets The camera contrast used on this material.
  80546. */
  80547. set: function (value) {
  80548. this._imageProcessingConfiguration.contrast = value;
  80549. },
  80550. enumerable: true,
  80551. configurable: true
  80552. });
  80553. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  80554. /**
  80555. * Gets the Color Grading 2D Lookup Texture.
  80556. */
  80557. get: function () {
  80558. return this._imageProcessingConfiguration.colorGradingTexture;
  80559. },
  80560. /**
  80561. * Sets the Color Grading 2D Lookup Texture.
  80562. */
  80563. set: function (value) {
  80564. this.imageProcessingConfiguration.colorGradingTexture = value;
  80565. },
  80566. enumerable: true,
  80567. configurable: true
  80568. });
  80569. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  80570. /**
  80571. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  80572. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  80573. * 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;
  80574. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  80575. */
  80576. get: function () {
  80577. return this.imageProcessingConfiguration.colorCurves;
  80578. },
  80579. /**
  80580. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  80581. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  80582. * 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;
  80583. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  80584. */
  80585. set: function (value) {
  80586. this.imageProcessingConfiguration.colorCurves = value;
  80587. },
  80588. enumerable: true,
  80589. configurable: true
  80590. });
  80591. /**
  80592. * The entire material has been created in order to prevent overdraw.
  80593. * @returns false
  80594. */
  80595. BackgroundMaterial.prototype.needAlphaTesting = function () {
  80596. return true;
  80597. };
  80598. /**
  80599. * The entire material has been created in order to prevent overdraw.
  80600. * @returns true if blending is enable
  80601. */
  80602. BackgroundMaterial.prototype.needAlphaBlending = function () {
  80603. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  80604. };
  80605. /**
  80606. * Checks wether the material is ready to be rendered for a given mesh.
  80607. * @param mesh The mesh to render
  80608. * @param subMesh The submesh to check against
  80609. * @param useInstances Specify wether or not the material is used with instances
  80610. */
  80611. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  80612. var _this = this;
  80613. if (useInstances === void 0) { useInstances = false; }
  80614. if (subMesh.effect && this.isFrozen) {
  80615. if (this._wasPreviouslyReady) {
  80616. return true;
  80617. }
  80618. }
  80619. if (!subMesh._materialDefines) {
  80620. subMesh._materialDefines = new BackgroundMaterialDefines();
  80621. }
  80622. var scene = this.getScene();
  80623. var defines = subMesh._materialDefines;
  80624. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  80625. if (defines._renderId === scene.getRenderId()) {
  80626. return true;
  80627. }
  80628. }
  80629. var engine = scene.getEngine();
  80630. // Lights
  80631. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  80632. defines._needNormals = true;
  80633. // Textures
  80634. if (defines._areTexturesDirty) {
  80635. defines._needUVs = false;
  80636. if (scene.texturesEnabled) {
  80637. if (scene.getEngine().getCaps().textureLOD) {
  80638. defines.TEXTURELODSUPPORT = true;
  80639. }
  80640. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80641. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  80642. return false;
  80643. }
  80644. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  80645. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  80646. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  80647. defines.OPACITYFRESNEL = this._opacityFresnel;
  80648. }
  80649. else {
  80650. defines.DIFFUSE = false;
  80651. defines.DIFFUSEHASALPHA = false;
  80652. defines.GAMMADIFFUSE = false;
  80653. defines.OPACITYFRESNEL = false;
  80654. }
  80655. var reflectionTexture = this._reflectionTexture;
  80656. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80657. if (!reflectionTexture.isReadyOrNotBlocking()) {
  80658. return false;
  80659. }
  80660. defines.REFLECTION = true;
  80661. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  80662. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  80663. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  80664. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  80665. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  80666. defines.INVERTCUBICMAP = true;
  80667. }
  80668. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  80669. switch (reflectionTexture.coordinatesMode) {
  80670. case BABYLON.Texture.CUBIC_MODE:
  80671. case BABYLON.Texture.INVCUBIC_MODE:
  80672. defines.REFLECTIONMAP_CUBIC = true;
  80673. break;
  80674. case BABYLON.Texture.EXPLICIT_MODE:
  80675. defines.REFLECTIONMAP_EXPLICIT = true;
  80676. break;
  80677. case BABYLON.Texture.PLANAR_MODE:
  80678. defines.REFLECTIONMAP_PLANAR = true;
  80679. break;
  80680. case BABYLON.Texture.PROJECTION_MODE:
  80681. defines.REFLECTIONMAP_PROJECTION = true;
  80682. break;
  80683. case BABYLON.Texture.SKYBOX_MODE:
  80684. defines.REFLECTIONMAP_SKYBOX = true;
  80685. break;
  80686. case BABYLON.Texture.SPHERICAL_MODE:
  80687. defines.REFLECTIONMAP_SPHERICAL = true;
  80688. break;
  80689. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  80690. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  80691. break;
  80692. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  80693. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  80694. break;
  80695. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  80696. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  80697. break;
  80698. }
  80699. if (this.reflectionFresnel) {
  80700. defines.REFLECTIONFRESNEL = true;
  80701. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  80702. this._reflectionControls.x = this.reflectionAmount;
  80703. this._reflectionControls.y = this.reflectionReflectance0;
  80704. this._reflectionControls.z = this.reflectionReflectance90;
  80705. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  80706. }
  80707. else {
  80708. defines.REFLECTIONFRESNEL = false;
  80709. defines.REFLECTIONFALLOFF = false;
  80710. }
  80711. }
  80712. else {
  80713. defines.REFLECTION = false;
  80714. defines.REFLECTIONFALLOFF = false;
  80715. defines.REFLECTIONBLUR = false;
  80716. defines.REFLECTIONMAP_3D = false;
  80717. defines.REFLECTIONMAP_SPHERICAL = false;
  80718. defines.REFLECTIONMAP_PLANAR = false;
  80719. defines.REFLECTIONMAP_CUBIC = false;
  80720. defines.REFLECTIONMAP_PROJECTION = false;
  80721. defines.REFLECTIONMAP_SKYBOX = false;
  80722. defines.REFLECTIONMAP_EXPLICIT = false;
  80723. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  80724. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  80725. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  80726. defines.INVERTCUBICMAP = false;
  80727. defines.REFLECTIONMAP_OPPOSITEZ = false;
  80728. defines.LODINREFLECTIONALPHA = false;
  80729. defines.GAMMAREFLECTION = false;
  80730. }
  80731. }
  80732. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  80733. defines.USERGBCOLOR = this._useRGBColor;
  80734. defines.NOISE = this._enableNoise;
  80735. }
  80736. if (defines._areImageProcessingDirty) {
  80737. if (!this._imageProcessingConfiguration.isReady()) {
  80738. return false;
  80739. }
  80740. this._imageProcessingConfiguration.prepareDefines(defines);
  80741. }
  80742. // Misc.
  80743. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  80744. // Values that need to be evaluated on every frame
  80745. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  80746. // Attribs
  80747. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  80748. if (mesh) {
  80749. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80750. mesh.createNormals(true);
  80751. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  80752. }
  80753. }
  80754. }
  80755. // Get correct effect
  80756. if (defines.isDirty) {
  80757. defines.markAsProcessed();
  80758. scene.resetCachedMaterial();
  80759. // Fallbacks
  80760. var fallbacks = new BABYLON.EffectFallbacks();
  80761. if (defines.FOG) {
  80762. fallbacks.addFallback(0, "FOG");
  80763. }
  80764. if (defines.POINTSIZE) {
  80765. fallbacks.addFallback(1, "POINTSIZE");
  80766. }
  80767. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  80768. if (defines.NUM_BONE_INFLUENCERS > 0) {
  80769. fallbacks.addCPUSkinningFallback(0, mesh);
  80770. }
  80771. //Attributes
  80772. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80773. if (defines.NORMAL) {
  80774. attribs.push(BABYLON.VertexBuffer.NormalKind);
  80775. }
  80776. if (defines.UV1) {
  80777. attribs.push(BABYLON.VertexBuffer.UVKind);
  80778. }
  80779. if (defines.UV2) {
  80780. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80781. }
  80782. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  80783. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  80784. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  80785. "vFogInfos", "vFogColor", "pointSize",
  80786. "vClipPlane", "mBones",
  80787. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  80788. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  80789. "shadowLevel", "alpha",
  80790. "vBackgroundCenter", "vReflectionControl",
  80791. "vDiffuseInfos", "diffuseMatrix",
  80792. ];
  80793. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  80794. var uniformBuffers = ["Material", "Scene"];
  80795. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  80796. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  80797. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  80798. uniformsNames: uniforms,
  80799. uniformBuffersNames: uniformBuffers,
  80800. samplers: samplers,
  80801. defines: defines,
  80802. maxSimultaneousLights: this._maxSimultaneousLights
  80803. });
  80804. var onCompiled = function (effect) {
  80805. if (_this.onCompiled) {
  80806. _this.onCompiled(effect);
  80807. }
  80808. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  80809. };
  80810. var join = defines.toString();
  80811. subMesh.setEffect(scene.getEngine().createEffect("background", {
  80812. attributes: attribs,
  80813. uniformsNames: uniforms,
  80814. uniformBuffersNames: uniformBuffers,
  80815. samplers: samplers,
  80816. defines: join,
  80817. fallbacks: fallbacks,
  80818. onCompiled: onCompiled,
  80819. onError: this.onError,
  80820. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  80821. }, engine), defines);
  80822. this.buildUniformLayout();
  80823. }
  80824. if (!subMesh.effect || !subMesh.effect.isReady()) {
  80825. return false;
  80826. }
  80827. defines._renderId = scene.getRenderId();
  80828. this._wasPreviouslyReady = true;
  80829. return true;
  80830. };
  80831. /**
  80832. * Build the uniform buffer used in the material.
  80833. */
  80834. BackgroundMaterial.prototype.buildUniformLayout = function () {
  80835. // Order is important !
  80836. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  80837. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  80838. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  80839. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  80840. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  80841. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  80842. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  80843. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  80844. this._uniformBuffer.addUniform("pointSize", 1);
  80845. this._uniformBuffer.addUniform("shadowLevel", 1);
  80846. this._uniformBuffer.addUniform("alpha", 1);
  80847. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  80848. this._uniformBuffer.addUniform("vReflectionControl", 4);
  80849. this._uniformBuffer.create();
  80850. };
  80851. /**
  80852. * Unbind the material.
  80853. */
  80854. BackgroundMaterial.prototype.unbind = function () {
  80855. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  80856. this._uniformBuffer.setTexture("diffuseSampler", null);
  80857. }
  80858. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  80859. this._uniformBuffer.setTexture("reflectionSampler", null);
  80860. }
  80861. _super.prototype.unbind.call(this);
  80862. };
  80863. /**
  80864. * Bind only the world matrix to the material.
  80865. * @param world The world matrix to bind.
  80866. */
  80867. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  80868. this._activeEffect.setMatrix("world", world);
  80869. };
  80870. /**
  80871. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  80872. * @param world The world matrix to bind.
  80873. * @param subMesh The submesh to bind for.
  80874. */
  80875. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  80876. var scene = this.getScene();
  80877. var defines = subMesh._materialDefines;
  80878. if (!defines) {
  80879. return;
  80880. }
  80881. var effect = subMesh.effect;
  80882. if (!effect) {
  80883. return;
  80884. }
  80885. this._activeEffect = effect;
  80886. // Matrices
  80887. this.bindOnlyWorldMatrix(world);
  80888. // Bones
  80889. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  80890. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  80891. if (mustRebind) {
  80892. this._uniformBuffer.bindToEffect(effect, "Material");
  80893. this.bindViewProjection(effect);
  80894. var reflectionTexture = this._reflectionTexture;
  80895. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  80896. // Texture uniforms
  80897. if (scene.texturesEnabled) {
  80898. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80899. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  80900. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  80901. }
  80902. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80903. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  80904. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  80905. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  80906. }
  80907. }
  80908. if (this.shadowLevel > 0) {
  80909. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  80910. }
  80911. this._uniformBuffer.updateFloat("alpha", this.alpha);
  80912. // Point size
  80913. if (this.pointsCloud) {
  80914. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  80915. }
  80916. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  80917. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  80918. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  80919. }
  80920. // Textures
  80921. if (scene.texturesEnabled) {
  80922. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80923. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  80924. }
  80925. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80926. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  80927. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  80928. }
  80929. else if (!defines.REFLECTIONBLUR) {
  80930. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  80931. }
  80932. else {
  80933. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  80934. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  80935. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  80936. }
  80937. if (defines.REFLECTIONFRESNEL) {
  80938. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  80939. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  80940. }
  80941. }
  80942. }
  80943. // Clip plane
  80944. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  80945. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  80946. }
  80947. if (mustRebind || !this.isFrozen) {
  80948. if (scene.lightsEnabled) {
  80949. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  80950. }
  80951. // View
  80952. this.bindView(effect);
  80953. // Fog
  80954. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  80955. // image processing
  80956. this._imageProcessingConfiguration.bind(this._activeEffect);
  80957. }
  80958. this._uniformBuffer.update();
  80959. this._afterBind(mesh);
  80960. };
  80961. /**
  80962. * Dispose the material.
  80963. * @forceDisposeEffect Force disposal of the associated effect.
  80964. * @forceDisposeTextures Force disposal of the associated textures.
  80965. */
  80966. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  80967. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  80968. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  80969. if (forceDisposeTextures) {
  80970. if (this.diffuseTexture) {
  80971. this.diffuseTexture.dispose();
  80972. }
  80973. if (this.reflectionTexture) {
  80974. this.reflectionTexture.dispose();
  80975. }
  80976. }
  80977. this._renderTargets.dispose();
  80978. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80979. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80980. }
  80981. _super.prototype.dispose.call(this, forceDisposeEffect);
  80982. };
  80983. /**
  80984. * Clones the material.
  80985. * @name The cloned name.
  80986. * @returns The cloned material.
  80987. */
  80988. BackgroundMaterial.prototype.clone = function (name) {
  80989. var _this = this;
  80990. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  80991. };
  80992. /**
  80993. * Serializes the current material to its JSON representation.
  80994. * @returns The JSON representation.
  80995. */
  80996. BackgroundMaterial.prototype.serialize = function () {
  80997. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80998. serializationObject.customType = "BABYLON.BackgroundMaterial";
  80999. return serializationObject;
  81000. };
  81001. /**
  81002. * Gets the class name of the material
  81003. * @returns "BackgroundMaterial"
  81004. */
  81005. BackgroundMaterial.prototype.getClassName = function () {
  81006. return "BackgroundMaterial";
  81007. };
  81008. /**
  81009. * Parse a JSON input to create back a background material.
  81010. * @param source
  81011. * @param scene
  81012. * @param rootUrl
  81013. * @returns the instantiated BackgroundMaterial.
  81014. */
  81015. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  81016. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  81017. };
  81018. /**
  81019. * Standard reflectance value at parallel view angle.
  81020. */
  81021. BackgroundMaterial.standardReflectance0 = 0.05;
  81022. /**
  81023. * Standard reflectance value at grazing angle.
  81024. */
  81025. BackgroundMaterial.standardReflectance90 = 0.5;
  81026. __decorate([
  81027. BABYLON.serializeAsColor3()
  81028. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  81029. __decorate([
  81030. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81031. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  81032. __decorate([
  81033. BABYLON.serialize()
  81034. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  81035. __decorate([
  81036. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81037. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  81038. __decorate([
  81039. BABYLON.serializeAsColor3()
  81040. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  81041. __decorate([
  81042. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81043. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  81044. __decorate([
  81045. BABYLON.serialize()
  81046. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  81047. __decorate([
  81048. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81049. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  81050. __decorate([
  81051. BABYLON.serializeAsColor3()
  81052. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  81053. __decorate([
  81054. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81055. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  81056. __decorate([
  81057. BABYLON.serialize()
  81058. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  81059. __decorate([
  81060. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81061. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  81062. __decorate([
  81063. BABYLON.serializeAsTexture()
  81064. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  81065. __decorate([
  81066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81067. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  81068. __decorate([
  81069. BABYLON.serialize()
  81070. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  81071. __decorate([
  81072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81073. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  81074. __decorate([
  81075. BABYLON.serializeAsTexture()
  81076. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  81077. __decorate([
  81078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81079. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  81080. __decorate([
  81081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81082. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  81083. __decorate([
  81084. BABYLON.serialize()
  81085. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  81086. __decorate([
  81087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81088. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  81089. __decorate([
  81090. BABYLON.serialize()
  81091. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  81092. __decorate([
  81093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81094. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  81095. __decorate([
  81096. BABYLON.serializeAsVector3()
  81097. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  81098. __decorate([
  81099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81100. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  81101. __decorate([
  81102. BABYLON.serialize()
  81103. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  81104. __decorate([
  81105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81106. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  81107. __decorate([
  81108. BABYLON.serialize()
  81109. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  81110. __decorate([
  81111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81112. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  81113. __decorate([
  81114. BABYLON.serialize()
  81115. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  81116. __decorate([
  81117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81118. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  81119. __decorate([
  81120. BABYLON.serialize()
  81121. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  81122. __decorate([
  81123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81124. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  81125. __decorate([
  81126. BABYLON.serialize()
  81127. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  81128. __decorate([
  81129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81130. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  81131. __decorate([
  81132. BABYLON.serialize()
  81133. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  81134. __decorate([
  81135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81136. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  81137. __decorate([
  81138. BABYLON.serialize()
  81139. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  81140. __decorate([
  81141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81142. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  81143. __decorate([
  81144. BABYLON.serialize()
  81145. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  81146. __decorate([
  81147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81148. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  81149. __decorate([
  81150. BABYLON.serialize()
  81151. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  81152. __decorate([
  81153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81154. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  81155. __decorate([
  81156. BABYLON.serializeAsImageProcessingConfiguration()
  81157. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  81158. return BackgroundMaterial;
  81159. }(BABYLON.PushMaterial));
  81160. BABYLON.BackgroundMaterial = BackgroundMaterial;
  81161. })(BABYLON || (BABYLON = {}));
  81162. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  81163. var __assign = (this && this.__assign) || Object.assign || function(t) {
  81164. for (var s, i = 1, n = arguments.length; i < n; i++) {
  81165. s = arguments[i];
  81166. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  81167. t[p] = s[p];
  81168. }
  81169. return t;
  81170. };
  81171. var BABYLON;
  81172. (function (BABYLON) {
  81173. /**
  81174. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  81175. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  81176. * It also helps with the default setup of your imageProcessing configuration.
  81177. */
  81178. var EnvironmentHelper = /** @class */ (function () {
  81179. /**
  81180. * constructor
  81181. * @param options
  81182. * @param scene The scene to add the material to
  81183. */
  81184. function EnvironmentHelper(options, scene) {
  81185. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  81186. this._scene = scene;
  81187. this._setupBackground();
  81188. this._setupImageProcessing();
  81189. }
  81190. /**
  81191. * Creates the default options for the helper.
  81192. */
  81193. EnvironmentHelper._getDefaultOptions = function () {
  81194. return {
  81195. createGround: true,
  81196. groundSize: 15,
  81197. groundTexture: this._groundTextureCDNUrl,
  81198. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  81199. groundOpacity: 0.9,
  81200. enableGroundShadow: true,
  81201. groundShadowLevel: 0.5,
  81202. enableGroundMirror: false,
  81203. groundMirrorSizeRatio: 0.3,
  81204. groundMirrorBlurKernel: 64,
  81205. groundMirrorAmount: 1,
  81206. groundMirrorFresnelWeight: 1,
  81207. groundMirrorFallOffDistance: 0,
  81208. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  81209. groundYBias: 0.00001,
  81210. createSkybox: true,
  81211. skyboxSize: 20,
  81212. skyboxTexture: this._skyboxTextureCDNUrl,
  81213. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  81214. backgroundYRotation: 0,
  81215. sizeAuto: true,
  81216. rootPosition: BABYLON.Vector3.Zero(),
  81217. setupImageProcessing: true,
  81218. environmentTexture: this._environmentTextureCDNUrl,
  81219. cameraExposure: 0.8,
  81220. cameraContrast: 1.2,
  81221. toneMappingEnabled: true,
  81222. };
  81223. };
  81224. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  81225. /**
  81226. * Gets the root mesh created by the helper.
  81227. */
  81228. get: function () {
  81229. return this._rootMesh;
  81230. },
  81231. enumerable: true,
  81232. configurable: true
  81233. });
  81234. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  81235. /**
  81236. * Gets the skybox created by the helper.
  81237. */
  81238. get: function () {
  81239. return this._skybox;
  81240. },
  81241. enumerable: true,
  81242. configurable: true
  81243. });
  81244. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  81245. /**
  81246. * Gets the skybox texture created by the helper.
  81247. */
  81248. get: function () {
  81249. return this._skyboxTexture;
  81250. },
  81251. enumerable: true,
  81252. configurable: true
  81253. });
  81254. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  81255. /**
  81256. * Gets the skybox material created by the helper.
  81257. */
  81258. get: function () {
  81259. return this._skyboxMaterial;
  81260. },
  81261. enumerable: true,
  81262. configurable: true
  81263. });
  81264. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  81265. /**
  81266. * Gets the ground mesh created by the helper.
  81267. */
  81268. get: function () {
  81269. return this._ground;
  81270. },
  81271. enumerable: true,
  81272. configurable: true
  81273. });
  81274. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  81275. /**
  81276. * Gets the ground texture created by the helper.
  81277. */
  81278. get: function () {
  81279. return this._groundTexture;
  81280. },
  81281. enumerable: true,
  81282. configurable: true
  81283. });
  81284. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  81285. /**
  81286. * Gets the ground mirror created by the helper.
  81287. */
  81288. get: function () {
  81289. return this._groundMirror;
  81290. },
  81291. enumerable: true,
  81292. configurable: true
  81293. });
  81294. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  81295. /**
  81296. * Gets the ground mirror render list to helps pushing the meshes
  81297. * you wish in the ground reflection.
  81298. */
  81299. get: function () {
  81300. if (this._groundMirror) {
  81301. return this._groundMirror.renderList;
  81302. }
  81303. return null;
  81304. },
  81305. enumerable: true,
  81306. configurable: true
  81307. });
  81308. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  81309. /**
  81310. * Gets the ground material created by the helper.
  81311. */
  81312. get: function () {
  81313. return this._groundMaterial;
  81314. },
  81315. enumerable: true,
  81316. configurable: true
  81317. });
  81318. /**
  81319. * Updates the background according to the new options
  81320. * @param options
  81321. */
  81322. EnvironmentHelper.prototype.updateOptions = function (options) {
  81323. var newOptions = __assign({}, this._options, options);
  81324. if (this._ground && !newOptions.createGround) {
  81325. this._ground.dispose();
  81326. this._ground = null;
  81327. }
  81328. if (this._groundMaterial && !newOptions.createGround) {
  81329. this._groundMaterial.dispose();
  81330. this._groundMaterial = null;
  81331. }
  81332. if (this._groundTexture) {
  81333. if (this._options.groundTexture != newOptions.groundTexture) {
  81334. this._groundTexture.dispose();
  81335. this._groundTexture = null;
  81336. }
  81337. }
  81338. if (this._skybox && !newOptions.createSkybox) {
  81339. this._skybox.dispose();
  81340. this._skybox = null;
  81341. }
  81342. if (this._skyboxMaterial && !newOptions.createSkybox) {
  81343. this._skyboxMaterial.dispose();
  81344. this._skyboxMaterial = null;
  81345. }
  81346. if (this._skyboxTexture) {
  81347. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  81348. this._skyboxTexture.dispose();
  81349. this._skyboxTexture = null;
  81350. }
  81351. }
  81352. if (this._groundMirror && !newOptions.enableGroundMirror) {
  81353. this._groundMirror.dispose();
  81354. this._groundMirror = null;
  81355. }
  81356. if (this._scene.environmentTexture) {
  81357. if (this._options.environmentTexture != newOptions.environmentTexture) {
  81358. this._scene.environmentTexture.dispose();
  81359. }
  81360. }
  81361. this._options = newOptions;
  81362. this._setupBackground();
  81363. this._setupImageProcessing();
  81364. };
  81365. /**
  81366. * Sets the primary color of all the available elements.
  81367. * @param color
  81368. */
  81369. EnvironmentHelper.prototype.setMainColor = function (color) {
  81370. if (this.groundMaterial) {
  81371. this.groundMaterial.primaryColor = color;
  81372. }
  81373. if (this.skyboxMaterial) {
  81374. this.skyboxMaterial.primaryColor = color;
  81375. }
  81376. if (this.groundMirror) {
  81377. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  81378. }
  81379. };
  81380. /**
  81381. * Setup the image processing according to the specified options.
  81382. */
  81383. EnvironmentHelper.prototype._setupImageProcessing = function () {
  81384. if (this._options.setupImageProcessing) {
  81385. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  81386. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  81387. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  81388. this._setupEnvironmentTexture();
  81389. }
  81390. };
  81391. /**
  81392. * Setup the environment texture according to the specified options.
  81393. */
  81394. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  81395. if (this._scene.environmentTexture) {
  81396. return;
  81397. }
  81398. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  81399. this._scene.environmentTexture = this._options.environmentTexture;
  81400. return;
  81401. }
  81402. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  81403. this._scene.environmentTexture = environmentTexture;
  81404. };
  81405. /**
  81406. * Setup the background according to the specified options.
  81407. */
  81408. EnvironmentHelper.prototype._setupBackground = function () {
  81409. if (!this._rootMesh) {
  81410. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  81411. }
  81412. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  81413. var sceneSize = this._getSceneSize();
  81414. if (this._options.createGround) {
  81415. this._setupGround(sceneSize);
  81416. this._setupGroundMaterial();
  81417. this._setupGroundDiffuseTexture();
  81418. if (this._options.enableGroundMirror) {
  81419. this._setupGroundMirrorTexture(sceneSize);
  81420. }
  81421. this._setupMirrorInGroundMaterial();
  81422. }
  81423. if (this._options.createSkybox) {
  81424. this._setupSkybox(sceneSize);
  81425. this._setupSkyboxMaterial();
  81426. this._setupSkyboxReflectionTexture();
  81427. }
  81428. this._rootMesh.position.x = sceneSize.rootPosition.x;
  81429. this._rootMesh.position.z = sceneSize.rootPosition.z;
  81430. this._rootMesh.position.y = sceneSize.rootPosition.y;
  81431. };
  81432. /**
  81433. * Get the scene sizes according to the setup.
  81434. */
  81435. EnvironmentHelper.prototype._getSceneSize = function () {
  81436. var groundSize = this._options.groundSize;
  81437. var skyboxSize = this._options.skyboxSize;
  81438. var rootPosition = this._options.rootPosition;
  81439. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  81440. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  81441. }
  81442. var sceneExtends = this._scene.getWorldExtends();
  81443. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  81444. if (this._options.sizeAuto) {
  81445. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  81446. this._scene.activeCamera.upperRadiusLimit) {
  81447. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  81448. skyboxSize = groundSize;
  81449. }
  81450. var sceneDiagonalLenght = sceneDiagonal.length();
  81451. if (sceneDiagonalLenght > groundSize) {
  81452. groundSize = sceneDiagonalLenght * 2;
  81453. skyboxSize = groundSize;
  81454. }
  81455. // 10 % bigger.
  81456. groundSize *= 1.1;
  81457. skyboxSize *= 1.5;
  81458. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  81459. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  81460. }
  81461. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  81462. };
  81463. /**
  81464. * Setup the ground according to the specified options.
  81465. */
  81466. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  81467. var _this = this;
  81468. if (!this._ground) {
  81469. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  81470. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  81471. this._ground.parent = this._rootMesh;
  81472. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  81473. }
  81474. this._ground.receiveShadows = this._options.enableGroundShadow;
  81475. };
  81476. /**
  81477. * Setup the ground material according to the specified options.
  81478. */
  81479. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  81480. if (!this._groundMaterial) {
  81481. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  81482. }
  81483. this._groundMaterial.alpha = this._options.groundOpacity;
  81484. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  81485. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  81486. this._groundMaterial.primaryLevel = 1;
  81487. this._groundMaterial.primaryColor = this._options.groundColor;
  81488. this._groundMaterial.secondaryLevel = 0;
  81489. this._groundMaterial.tertiaryLevel = 0;
  81490. this._groundMaterial.useRGBColor = false;
  81491. this._groundMaterial.enableNoise = true;
  81492. if (this._ground) {
  81493. this._ground.material = this._groundMaterial;
  81494. }
  81495. };
  81496. /**
  81497. * Setup the ground diffuse texture according to the specified options.
  81498. */
  81499. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  81500. if (!this._groundMaterial) {
  81501. return;
  81502. }
  81503. if (this._groundTexture) {
  81504. return;
  81505. }
  81506. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  81507. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  81508. return;
  81509. }
  81510. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  81511. diffuseTexture.gammaSpace = false;
  81512. diffuseTexture.hasAlpha = true;
  81513. this._groundMaterial.diffuseTexture = diffuseTexture;
  81514. };
  81515. /**
  81516. * Setup the ground mirror texture according to the specified options.
  81517. */
  81518. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  81519. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81520. if (!this._groundMirror) {
  81521. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  81522. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  81523. this._groundMirror.anisotropicFilteringLevel = 1;
  81524. this._groundMirror.wrapU = wrapping;
  81525. this._groundMirror.wrapV = wrapping;
  81526. this._groundMirror.gammaSpace = false;
  81527. if (this._groundMirror.renderList) {
  81528. for (var i = 0; i < this._scene.meshes.length; i++) {
  81529. var mesh = this._scene.meshes[i];
  81530. if (mesh !== this._ground &&
  81531. mesh !== this._skybox &&
  81532. mesh !== this._rootMesh) {
  81533. this._groundMirror.renderList.push(mesh);
  81534. }
  81535. }
  81536. }
  81537. }
  81538. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  81539. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  81540. };
  81541. /**
  81542. * Setup the ground to receive the mirror texture.
  81543. */
  81544. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  81545. if (this._groundMaterial) {
  81546. this._groundMaterial.reflectionTexture = this._groundMirror;
  81547. this._groundMaterial.reflectionFresnel = true;
  81548. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  81549. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  81550. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  81551. }
  81552. };
  81553. /**
  81554. * Setup the skybox according to the specified options.
  81555. */
  81556. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  81557. var _this = this;
  81558. if (!this._skybox) {
  81559. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  81560. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  81561. }
  81562. this._skybox.parent = this._rootMesh;
  81563. };
  81564. /**
  81565. * Setup the skybox material according to the specified options.
  81566. */
  81567. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  81568. if (!this._skybox) {
  81569. return;
  81570. }
  81571. if (!this._skyboxMaterial) {
  81572. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  81573. }
  81574. this._skyboxMaterial.useRGBColor = false;
  81575. this._skyboxMaterial.primaryLevel = 1;
  81576. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  81577. this._skyboxMaterial.secondaryLevel = 0;
  81578. this._skyboxMaterial.tertiaryLevel = 0;
  81579. this._skyboxMaterial.enableNoise = true;
  81580. this._skybox.material = this._skyboxMaterial;
  81581. };
  81582. /**
  81583. * Setup the skybox reflection texture according to the specified options.
  81584. */
  81585. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  81586. if (!this._skyboxMaterial) {
  81587. return;
  81588. }
  81589. if (this._skyboxTexture) {
  81590. return;
  81591. }
  81592. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  81593. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  81594. return;
  81595. }
  81596. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  81597. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  81598. this._skyboxTexture.gammaSpace = false;
  81599. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  81600. };
  81601. /**
  81602. * Dispose all the elements created by the Helper.
  81603. */
  81604. EnvironmentHelper.prototype.dispose = function () {
  81605. if (this._groundMaterial) {
  81606. this._groundMaterial.dispose(true, true);
  81607. }
  81608. if (this._skyboxMaterial) {
  81609. this._skyboxMaterial.dispose(true, true);
  81610. }
  81611. this._rootMesh.dispose(false);
  81612. };
  81613. /**
  81614. * Default ground texture URL.
  81615. */
  81616. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  81617. /**
  81618. * Default skybox texture URL.
  81619. */
  81620. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  81621. /**
  81622. * Default environment texture URL.
  81623. */
  81624. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  81625. return EnvironmentHelper;
  81626. }());
  81627. BABYLON.EnvironmentHelper = EnvironmentHelper;
  81628. })(BABYLON || (BABYLON = {}));
  81629. //# sourceMappingURL=babylon.environmentHelper.js.map
  81630. 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}"};
  81631. 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};"};
  81632. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  81633. var BABYLON;
  81634. (function (BABYLON) {
  81635. var GridMaterialDefines = /** @class */ (function (_super) {
  81636. __extends(GridMaterialDefines, _super);
  81637. function GridMaterialDefines() {
  81638. var _this = _super.call(this) || this;
  81639. _this.TRANSPARENT = false;
  81640. _this.FOG = false;
  81641. _this.PREMULTIPLYALPHA = false;
  81642. _this.rebuild();
  81643. return _this;
  81644. }
  81645. return GridMaterialDefines;
  81646. }(BABYLON.MaterialDefines));
  81647. /**
  81648. * The grid materials allows you to wrap any shape with a grid.
  81649. * Colors are customizable.
  81650. */
  81651. var GridMaterial = /** @class */ (function (_super) {
  81652. __extends(GridMaterial, _super);
  81653. /**
  81654. * constructor
  81655. * @param name The name given to the material in order to identify it afterwards.
  81656. * @param scene The scene the material is used in.
  81657. */
  81658. function GridMaterial(name, scene) {
  81659. var _this = _super.call(this, name, scene) || this;
  81660. /**
  81661. * Main color of the grid (e.g. between lines)
  81662. */
  81663. _this.mainColor = BABYLON.Color3.Black();
  81664. /**
  81665. * Color of the grid lines.
  81666. */
  81667. _this.lineColor = BABYLON.Color3.Teal();
  81668. /**
  81669. * The scale of the grid compared to unit.
  81670. */
  81671. _this.gridRatio = 1.0;
  81672. /**
  81673. * Allows setting an offset for the grid lines.
  81674. */
  81675. _this.gridOffset = BABYLON.Vector3.Zero();
  81676. /**
  81677. * The frequency of thicker lines.
  81678. */
  81679. _this.majorUnitFrequency = 10;
  81680. /**
  81681. * The visibility of minor units in the grid.
  81682. */
  81683. _this.minorUnitVisibility = 0.33;
  81684. /**
  81685. * The grid opacity outside of the lines.
  81686. */
  81687. _this.opacity = 1.0;
  81688. /**
  81689. * Determine RBG output is premultiplied by alpha value.
  81690. */
  81691. _this.preMultiplyAlpha = false;
  81692. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  81693. return _this;
  81694. }
  81695. /**
  81696. * Returns wehter or not the grid requires alpha blending.
  81697. */
  81698. GridMaterial.prototype.needAlphaBlending = function () {
  81699. return this.opacity < 1.0;
  81700. };
  81701. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  81702. return this.needAlphaBlending();
  81703. };
  81704. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  81705. if (this.isFrozen) {
  81706. if (this._wasPreviouslyReady && subMesh.effect) {
  81707. return true;
  81708. }
  81709. }
  81710. if (!subMesh._materialDefines) {
  81711. subMesh._materialDefines = new GridMaterialDefines();
  81712. }
  81713. var defines = subMesh._materialDefines;
  81714. var scene = this.getScene();
  81715. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  81716. if (this._renderId === scene.getRenderId()) {
  81717. return true;
  81718. }
  81719. }
  81720. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  81721. defines.TRANSPARENT = !defines.TRANSPARENT;
  81722. defines.markAsUnprocessed();
  81723. }
  81724. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  81725. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  81726. defines.markAsUnprocessed();
  81727. }
  81728. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  81729. // Get correct effect
  81730. if (defines.isDirty) {
  81731. defines.markAsProcessed();
  81732. scene.resetCachedMaterial();
  81733. // Attributes
  81734. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81735. // Defines
  81736. var join = defines.toString();
  81737. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  81738. }
  81739. if (!subMesh.effect || !subMesh.effect.isReady()) {
  81740. return false;
  81741. }
  81742. this._renderId = scene.getRenderId();
  81743. this._wasPreviouslyReady = true;
  81744. return true;
  81745. };
  81746. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  81747. var scene = this.getScene();
  81748. var defines = subMesh._materialDefines;
  81749. if (!defines) {
  81750. return;
  81751. }
  81752. var effect = subMesh.effect;
  81753. if (!effect) {
  81754. return;
  81755. }
  81756. this._activeEffect = effect;
  81757. // Matrices
  81758. this.bindOnlyWorldMatrix(world);
  81759. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  81760. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  81761. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  81762. // Uniforms
  81763. if (this._mustRebind(scene, effect)) {
  81764. this._activeEffect.setColor3("mainColor", this.mainColor);
  81765. this._activeEffect.setColor3("lineColor", this.lineColor);
  81766. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  81767. this._gridControl.x = this.gridRatio;
  81768. this._gridControl.y = Math.round(this.majorUnitFrequency);
  81769. this._gridControl.z = this.minorUnitVisibility;
  81770. this._gridControl.w = this.opacity;
  81771. this._activeEffect.setVector4("gridControl", this._gridControl);
  81772. }
  81773. // Fog
  81774. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  81775. this._afterBind(mesh, this._activeEffect);
  81776. };
  81777. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  81778. _super.prototype.dispose.call(this, forceDisposeEffect);
  81779. };
  81780. GridMaterial.prototype.clone = function (name) {
  81781. var _this = this;
  81782. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  81783. };
  81784. GridMaterial.prototype.serialize = function () {
  81785. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81786. serializationObject.customType = "BABYLON.GridMaterial";
  81787. return serializationObject;
  81788. };
  81789. GridMaterial.prototype.getClassName = function () {
  81790. return "GridMaterial";
  81791. };
  81792. GridMaterial.Parse = function (source, scene, rootUrl) {
  81793. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  81794. };
  81795. __decorate([
  81796. BABYLON.serializeAsColor3()
  81797. ], GridMaterial.prototype, "mainColor", void 0);
  81798. __decorate([
  81799. BABYLON.serializeAsColor3()
  81800. ], GridMaterial.prototype, "lineColor", void 0);
  81801. __decorate([
  81802. BABYLON.serialize()
  81803. ], GridMaterial.prototype, "gridRatio", void 0);
  81804. __decorate([
  81805. BABYLON.serializeAsColor3()
  81806. ], GridMaterial.prototype, "gridOffset", void 0);
  81807. __decorate([
  81808. BABYLON.serialize()
  81809. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  81810. __decorate([
  81811. BABYLON.serialize()
  81812. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  81813. __decorate([
  81814. BABYLON.serialize()
  81815. ], GridMaterial.prototype, "opacity", void 0);
  81816. __decorate([
  81817. BABYLON.serialize()
  81818. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  81819. return GridMaterial;
  81820. }(BABYLON.PushMaterial));
  81821. BABYLON.GridMaterial = GridMaterial;
  81822. })(BABYLON || (BABYLON = {}));
  81823. //# sourceMappingURL=babylon.gridmaterial.js.map
  81824. 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}";
  81825. 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}";
  81826. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  81827. var BABYLON;
  81828. (function (BABYLON) {
  81829. var GLTFLoaderCoordinateSystemMode;
  81830. (function (GLTFLoaderCoordinateSystemMode) {
  81831. /**
  81832. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  81833. */
  81834. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  81835. /**
  81836. * Sets the useRightHandedSystem flag on the scene.
  81837. */
  81838. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  81839. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  81840. var GLTFLoaderAnimationStartMode;
  81841. (function (GLTFLoaderAnimationStartMode) {
  81842. /**
  81843. * No animation will start.
  81844. */
  81845. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  81846. /**
  81847. * The first animation will start.
  81848. */
  81849. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  81850. /**
  81851. * All animations will start.
  81852. */
  81853. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  81854. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  81855. var GLTFFileLoader = /** @class */ (function () {
  81856. function GLTFFileLoader() {
  81857. // #region Common options
  81858. /**
  81859. * Raised when the asset has been parsed.
  81860. * The data.json property stores the glTF JSON.
  81861. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  81862. */
  81863. this.onParsedObservable = new BABYLON.Observable();
  81864. // #endregion
  81865. // #region V2 options
  81866. /**
  81867. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  81868. */
  81869. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  81870. /**
  81871. * The animation start mode (NONE, FIRST, ALL).
  81872. */
  81873. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  81874. /**
  81875. * Set to true to compile materials before raising the success callback.
  81876. */
  81877. this.compileMaterials = false;
  81878. /**
  81879. * Set to true to also compile materials with clip planes.
  81880. */
  81881. this.useClipPlane = false;
  81882. /**
  81883. * Set to true to compile shadow generators before raising the success callback.
  81884. */
  81885. this.compileShadowGenerators = false;
  81886. /**
  81887. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  81888. */
  81889. this.onMeshLoadedObservable = new BABYLON.Observable();
  81890. /**
  81891. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  81892. */
  81893. this.onTextureLoadedObservable = new BABYLON.Observable();
  81894. /**
  81895. * Raised when the loader creates a material after parsing the glTF properties of the material.
  81896. */
  81897. this.onMaterialLoadedObservable = new BABYLON.Observable();
  81898. /**
  81899. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  81900. * For assets with LODs, raised when all of the LODs are complete.
  81901. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  81902. */
  81903. this.onCompleteObservable = new BABYLON.Observable();
  81904. /**
  81905. * Raised when the loader is disposed.
  81906. */
  81907. this.onDisposeObservable = new BABYLON.Observable();
  81908. // #endregion
  81909. this._loader = null;
  81910. this.name = "gltf";
  81911. this.extensions = {
  81912. ".gltf": { isBinary: false },
  81913. ".glb": { isBinary: true }
  81914. };
  81915. }
  81916. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  81917. set: function (callback) {
  81918. if (this._onParsedObserver) {
  81919. this.onParsedObservable.remove(this._onParsedObserver);
  81920. }
  81921. this._onParsedObserver = this.onParsedObservable.add(callback);
  81922. },
  81923. enumerable: true,
  81924. configurable: true
  81925. });
  81926. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  81927. set: function (callback) {
  81928. if (this._onMeshLoadedObserver) {
  81929. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  81930. }
  81931. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  81932. },
  81933. enumerable: true,
  81934. configurable: true
  81935. });
  81936. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  81937. set: function (callback) {
  81938. if (this._onTextureLoadedObserver) {
  81939. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  81940. }
  81941. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  81942. },
  81943. enumerable: true,
  81944. configurable: true
  81945. });
  81946. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  81947. set: function (callback) {
  81948. if (this._onMaterialLoadedObserver) {
  81949. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  81950. }
  81951. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  81952. },
  81953. enumerable: true,
  81954. configurable: true
  81955. });
  81956. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  81957. set: function (callback) {
  81958. if (this._onCompleteObserver) {
  81959. this.onCompleteObservable.remove(this._onCompleteObserver);
  81960. }
  81961. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  81962. },
  81963. enumerable: true,
  81964. configurable: true
  81965. });
  81966. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  81967. set: function (callback) {
  81968. if (this._onDisposeObserver) {
  81969. this.onDisposeObservable.remove(this._onDisposeObserver);
  81970. }
  81971. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  81972. },
  81973. enumerable: true,
  81974. configurable: true
  81975. });
  81976. /**
  81977. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  81978. */
  81979. GLTFFileLoader.prototype.dispose = function () {
  81980. if (this._loader) {
  81981. this._loader.dispose();
  81982. this._loader = null;
  81983. }
  81984. this.onParsedObservable.clear();
  81985. this.onMeshLoadedObservable.clear();
  81986. this.onTextureLoadedObservable.clear();
  81987. this.onMaterialLoadedObservable.clear();
  81988. this.onCompleteObservable.clear();
  81989. this.onDisposeObservable.notifyObservers(this);
  81990. this.onDisposeObservable.clear();
  81991. };
  81992. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  81993. try {
  81994. var loaderData = this._parse(data);
  81995. this._loader = this._getLoader(loaderData);
  81996. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  81997. }
  81998. catch (e) {
  81999. if (onError) {
  82000. onError(e.message, e);
  82001. }
  82002. else {
  82003. BABYLON.Tools.Error(e.message);
  82004. }
  82005. }
  82006. };
  82007. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  82008. try {
  82009. var loaderData = this._parse(data);
  82010. this._loader = this._getLoader(loaderData);
  82011. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  82012. }
  82013. catch (e) {
  82014. if (onError) {
  82015. onError(e.message, e);
  82016. }
  82017. else {
  82018. BABYLON.Tools.Error(e.message);
  82019. }
  82020. }
  82021. };
  82022. GLTFFileLoader.prototype.loadAssetsAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  82023. try {
  82024. var loaderData = this._parse(data);
  82025. this._loader = this._getLoader(loaderData);
  82026. this._loader.importMeshAsync(null, scene, loaderData, rootUrl, function (meshes, particleSystems, skeletons) {
  82027. var container = new BABYLON.AssetContainer(scene);
  82028. Array.prototype.push.apply(container.meshes, meshes);
  82029. Array.prototype.push.apply(container.particleSystems, particleSystems);
  82030. Array.prototype.push.apply(container.skeletons, skeletons);
  82031. container.removeAllFromScene();
  82032. onSuccess(container);
  82033. }, onProgress, onError);
  82034. }
  82035. catch (e) {
  82036. if (onError) {
  82037. onError(e.message, e);
  82038. }
  82039. else {
  82040. BABYLON.Tools.Error(e.message);
  82041. }
  82042. }
  82043. };
  82044. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  82045. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  82046. };
  82047. GLTFFileLoader.prototype.createPlugin = function () {
  82048. return new GLTFFileLoader();
  82049. };
  82050. GLTFFileLoader.prototype._parse = function (data) {
  82051. var parsedData;
  82052. if (data instanceof ArrayBuffer) {
  82053. parsedData = GLTFFileLoader._parseBinary(data);
  82054. }
  82055. else {
  82056. parsedData = {
  82057. json: JSON.parse(data),
  82058. bin: null
  82059. };
  82060. }
  82061. this.onParsedObservable.notifyObservers(parsedData);
  82062. return parsedData;
  82063. };
  82064. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  82065. var _this = this;
  82066. var loaderVersion = { major: 2, minor: 0 };
  82067. var asset = loaderData.json.asset || {};
  82068. var version = GLTFFileLoader._parseVersion(asset.version);
  82069. if (!version) {
  82070. throw new Error("Invalid version: " + asset.version);
  82071. }
  82072. if (asset.minVersion !== undefined) {
  82073. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  82074. if (!minVersion) {
  82075. throw new Error("Invalid minimum version: " + asset.minVersion);
  82076. }
  82077. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  82078. throw new Error("Incompatible minimum version: " + asset.minVersion);
  82079. }
  82080. }
  82081. var createLoaders = {
  82082. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  82083. 2: GLTFFileLoader.CreateGLTFLoaderV2
  82084. };
  82085. var createLoader = createLoaders[version.major];
  82086. if (!createLoader) {
  82087. throw new Error("Unsupported version: " + asset.version);
  82088. }
  82089. var loader = createLoader();
  82090. loader.coordinateSystemMode = this.coordinateSystemMode;
  82091. loader.animationStartMode = this.animationStartMode;
  82092. loader.compileMaterials = this.compileMaterials;
  82093. loader.useClipPlane = this.useClipPlane;
  82094. loader.compileShadowGenerators = this.compileShadowGenerators;
  82095. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  82096. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  82097. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  82098. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  82099. return loader;
  82100. };
  82101. GLTFFileLoader._parseBinary = function (data) {
  82102. var Binary = {
  82103. Magic: 0x46546C67
  82104. };
  82105. var binaryReader = new BinaryReader(data);
  82106. var magic = binaryReader.readUint32();
  82107. if (magic !== Binary.Magic) {
  82108. throw new Error("Unexpected magic: " + magic);
  82109. }
  82110. var version = binaryReader.readUint32();
  82111. switch (version) {
  82112. case 1: return GLTFFileLoader._parseV1(binaryReader);
  82113. case 2: return GLTFFileLoader._parseV2(binaryReader);
  82114. }
  82115. throw new Error("Unsupported version: " + version);
  82116. };
  82117. GLTFFileLoader._parseV1 = function (binaryReader) {
  82118. var ContentFormat = {
  82119. JSON: 0
  82120. };
  82121. var length = binaryReader.readUint32();
  82122. if (length != binaryReader.getLength()) {
  82123. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  82124. }
  82125. var contentLength = binaryReader.readUint32();
  82126. var contentFormat = binaryReader.readUint32();
  82127. var content;
  82128. switch (contentFormat) {
  82129. case ContentFormat.JSON: {
  82130. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  82131. break;
  82132. }
  82133. default: {
  82134. throw new Error("Unexpected content format: " + contentFormat);
  82135. }
  82136. }
  82137. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  82138. var body = binaryReader.readUint8Array(bytesRemaining);
  82139. return {
  82140. json: content,
  82141. bin: body
  82142. };
  82143. };
  82144. GLTFFileLoader._parseV2 = function (binaryReader) {
  82145. var ChunkFormat = {
  82146. JSON: 0x4E4F534A,
  82147. BIN: 0x004E4942
  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. // JSON chunk
  82154. var chunkLength = binaryReader.readUint32();
  82155. var chunkFormat = binaryReader.readUint32();
  82156. if (chunkFormat !== ChunkFormat.JSON) {
  82157. throw new Error("First chunk format is not JSON");
  82158. }
  82159. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  82160. // Look for BIN chunk
  82161. var bin = null;
  82162. while (binaryReader.getPosition() < binaryReader.getLength()) {
  82163. var chunkLength_1 = binaryReader.readUint32();
  82164. var chunkFormat_1 = binaryReader.readUint32();
  82165. switch (chunkFormat_1) {
  82166. case ChunkFormat.JSON: {
  82167. throw new Error("Unexpected JSON chunk");
  82168. }
  82169. case ChunkFormat.BIN: {
  82170. bin = binaryReader.readUint8Array(chunkLength_1);
  82171. break;
  82172. }
  82173. default: {
  82174. // ignore unrecognized chunkFormat
  82175. binaryReader.skipBytes(chunkLength_1);
  82176. break;
  82177. }
  82178. }
  82179. }
  82180. return {
  82181. json: json,
  82182. bin: bin
  82183. };
  82184. };
  82185. GLTFFileLoader._parseVersion = function (version) {
  82186. if (version === "1.0" || version === "1.0.1") {
  82187. return {
  82188. major: 1,
  82189. minor: 0
  82190. };
  82191. }
  82192. var match = (version + "").match(/^(\d+)\.(\d+)/);
  82193. if (!match) {
  82194. return null;
  82195. }
  82196. return {
  82197. major: parseInt(match[1]),
  82198. minor: parseInt(match[2])
  82199. };
  82200. };
  82201. GLTFFileLoader._compareVersion = function (a, b) {
  82202. if (a.major > b.major)
  82203. return 1;
  82204. if (a.major < b.major)
  82205. return -1;
  82206. if (a.minor > b.minor)
  82207. return 1;
  82208. if (a.minor < b.minor)
  82209. return -1;
  82210. return 0;
  82211. };
  82212. GLTFFileLoader._decodeBufferToText = function (buffer) {
  82213. var result = "";
  82214. var length = buffer.byteLength;
  82215. for (var i = 0; i < length; i++) {
  82216. result += String.fromCharCode(buffer[i]);
  82217. }
  82218. return result;
  82219. };
  82220. // #endregion
  82221. // #region V1 options
  82222. GLTFFileLoader.IncrementalLoading = true;
  82223. GLTFFileLoader.HomogeneousCoordinates = false;
  82224. return GLTFFileLoader;
  82225. }());
  82226. BABYLON.GLTFFileLoader = GLTFFileLoader;
  82227. var BinaryReader = /** @class */ (function () {
  82228. function BinaryReader(arrayBuffer) {
  82229. this._arrayBuffer = arrayBuffer;
  82230. this._dataView = new DataView(arrayBuffer);
  82231. this._byteOffset = 0;
  82232. }
  82233. BinaryReader.prototype.getPosition = function () {
  82234. return this._byteOffset;
  82235. };
  82236. BinaryReader.prototype.getLength = function () {
  82237. return this._arrayBuffer.byteLength;
  82238. };
  82239. BinaryReader.prototype.readUint32 = function () {
  82240. var value = this._dataView.getUint32(this._byteOffset, true);
  82241. this._byteOffset += 4;
  82242. return value;
  82243. };
  82244. BinaryReader.prototype.readUint8Array = function (length) {
  82245. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  82246. this._byteOffset += length;
  82247. return value;
  82248. };
  82249. BinaryReader.prototype.skipBytes = function (length) {
  82250. this._byteOffset += length;
  82251. };
  82252. return BinaryReader;
  82253. }());
  82254. if (BABYLON.SceneLoader) {
  82255. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  82256. }
  82257. })(BABYLON || (BABYLON = {}));
  82258. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  82259. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82260. var BABYLON;
  82261. (function (BABYLON) {
  82262. var GLTF1;
  82263. (function (GLTF1) {
  82264. /**
  82265. * Enums
  82266. */
  82267. var EComponentType;
  82268. (function (EComponentType) {
  82269. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  82270. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  82271. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  82272. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  82273. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  82274. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  82275. var EShaderType;
  82276. (function (EShaderType) {
  82277. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  82278. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  82279. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  82280. var EParameterType;
  82281. (function (EParameterType) {
  82282. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  82283. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  82284. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  82285. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  82286. EParameterType[EParameterType["INT"] = 5124] = "INT";
  82287. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  82288. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  82289. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  82290. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  82291. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  82292. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  82293. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  82294. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  82295. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  82296. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  82297. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  82298. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  82299. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  82300. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  82301. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  82302. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  82303. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  82304. var ETextureWrapMode;
  82305. (function (ETextureWrapMode) {
  82306. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  82307. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  82308. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  82309. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  82310. var ETextureFilterType;
  82311. (function (ETextureFilterType) {
  82312. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  82313. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  82314. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  82315. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  82316. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  82317. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  82318. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  82319. var ETextureFormat;
  82320. (function (ETextureFormat) {
  82321. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  82322. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  82323. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  82324. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  82325. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  82326. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  82327. var ECullingType;
  82328. (function (ECullingType) {
  82329. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  82330. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  82331. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  82332. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  82333. var EBlendingFunction;
  82334. (function (EBlendingFunction) {
  82335. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  82336. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  82337. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  82338. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  82339. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  82340. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  82341. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  82342. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  82343. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  82344. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  82345. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  82346. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  82347. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  82348. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  82349. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  82350. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  82351. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  82352. })(BABYLON || (BABYLON = {}));
  82353. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  82354. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82355. var BABYLON;
  82356. (function (BABYLON) {
  82357. var GLTF1;
  82358. (function (GLTF1) {
  82359. /**
  82360. * Tokenizer. Used for shaders compatibility
  82361. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  82362. */
  82363. var ETokenType;
  82364. (function (ETokenType) {
  82365. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  82366. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  82367. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  82368. })(ETokenType || (ETokenType = {}));
  82369. var Tokenizer = /** @class */ (function () {
  82370. function Tokenizer(toParse) {
  82371. this._pos = 0;
  82372. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  82373. this._toParse = toParse;
  82374. this._maxPos = toParse.length;
  82375. }
  82376. Tokenizer.prototype.getNextToken = function () {
  82377. if (this.isEnd())
  82378. return ETokenType.END_OF_INPUT;
  82379. this.currentString = this.read();
  82380. this.currentToken = ETokenType.UNKNOWN;
  82381. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  82382. this.currentToken = ETokenType.IDENTIFIER;
  82383. this.currentIdentifier = this.currentString;
  82384. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  82385. this.currentIdentifier += this.currentString;
  82386. this.forward();
  82387. }
  82388. }
  82389. return this.currentToken;
  82390. };
  82391. Tokenizer.prototype.peek = function () {
  82392. return this._toParse[this._pos];
  82393. };
  82394. Tokenizer.prototype.read = function () {
  82395. return this._toParse[this._pos++];
  82396. };
  82397. Tokenizer.prototype.forward = function () {
  82398. this._pos++;
  82399. };
  82400. Tokenizer.prototype.isEnd = function () {
  82401. return this._pos >= this._maxPos;
  82402. };
  82403. return Tokenizer;
  82404. }());
  82405. /**
  82406. * Values
  82407. */
  82408. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  82409. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  82410. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  82411. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  82412. /**
  82413. * Parse
  82414. */
  82415. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  82416. for (var buf in parsedBuffers) {
  82417. var parsedBuffer = parsedBuffers[buf];
  82418. gltfRuntime.buffers[buf] = parsedBuffer;
  82419. gltfRuntime.buffersCount++;
  82420. }
  82421. };
  82422. var parseShaders = function (parsedShaders, gltfRuntime) {
  82423. for (var sha in parsedShaders) {
  82424. var parsedShader = parsedShaders[sha];
  82425. gltfRuntime.shaders[sha] = parsedShader;
  82426. gltfRuntime.shaderscount++;
  82427. }
  82428. };
  82429. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  82430. for (var object in parsedObjects) {
  82431. var parsedObject = parsedObjects[object];
  82432. gltfRuntime[runtimeProperty][object] = parsedObject;
  82433. }
  82434. };
  82435. /**
  82436. * Utils
  82437. */
  82438. var normalizeUVs = function (buffer) {
  82439. if (!buffer) {
  82440. return;
  82441. }
  82442. for (var i = 0; i < buffer.length / 2; i++) {
  82443. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  82444. }
  82445. };
  82446. var getAttribute = function (attributeParameter) {
  82447. if (attributeParameter.semantic === "NORMAL") {
  82448. return "normal";
  82449. }
  82450. else if (attributeParameter.semantic === "POSITION") {
  82451. return "position";
  82452. }
  82453. else if (attributeParameter.semantic === "JOINT") {
  82454. return "matricesIndices";
  82455. }
  82456. else if (attributeParameter.semantic === "WEIGHT") {
  82457. return "matricesWeights";
  82458. }
  82459. else if (attributeParameter.semantic === "COLOR") {
  82460. return "color";
  82461. }
  82462. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  82463. var channel = Number(attributeParameter.semantic.split("_")[1]);
  82464. return "uv" + (channel === 0 ? "" : channel + 1);
  82465. }
  82466. return null;
  82467. };
  82468. /**
  82469. * Loads and creates animations
  82470. */
  82471. var loadAnimations = function (gltfRuntime) {
  82472. for (var anim in gltfRuntime.animations) {
  82473. var animation = gltfRuntime.animations[anim];
  82474. if (!animation.channels || !animation.samplers) {
  82475. continue;
  82476. }
  82477. var lastAnimation = null;
  82478. for (var i = 0; i < animation.channels.length; i++) {
  82479. // Get parameters and load buffers
  82480. var channel = animation.channels[i];
  82481. var sampler = animation.samplers[channel.sampler];
  82482. if (!sampler) {
  82483. continue;
  82484. }
  82485. var inputData = null;
  82486. var outputData = null;
  82487. if (animation.parameters) {
  82488. inputData = animation.parameters[sampler.input];
  82489. outputData = animation.parameters[sampler.output];
  82490. }
  82491. else {
  82492. inputData = sampler.input;
  82493. outputData = sampler.output;
  82494. }
  82495. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  82496. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  82497. var targetID = channel.target.id;
  82498. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  82499. if (targetNode === null) {
  82500. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  82501. }
  82502. if (targetNode === null) {
  82503. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  82504. continue;
  82505. }
  82506. var isBone = targetNode instanceof BABYLON.Bone;
  82507. // Get target path (position, rotation or scaling)
  82508. var targetPath = channel.target.path;
  82509. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  82510. if (targetPathIndex !== -1) {
  82511. targetPath = babylonAnimationPaths[targetPathIndex];
  82512. }
  82513. // Determine animation type
  82514. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  82515. if (!isBone) {
  82516. if (targetPath === "rotationQuaternion") {
  82517. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  82518. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  82519. }
  82520. else {
  82521. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  82522. }
  82523. }
  82524. // Create animation and key frames
  82525. var babylonAnimation = null;
  82526. var keys = [];
  82527. var arrayOffset = 0;
  82528. var modifyKey = false;
  82529. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  82530. babylonAnimation = lastAnimation;
  82531. modifyKey = true;
  82532. }
  82533. if (!modifyKey) {
  82534. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  82535. }
  82536. // For each frame
  82537. for (var j = 0; j < bufferInput.length; j++) {
  82538. var value = null;
  82539. if (targetPath === "rotationQuaternion") {
  82540. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  82541. arrayOffset += 4;
  82542. }
  82543. else {
  82544. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  82545. arrayOffset += 3;
  82546. }
  82547. if (isBone) {
  82548. var bone = targetNode;
  82549. var translation = BABYLON.Vector3.Zero();
  82550. var rotationQuaternion = new BABYLON.Quaternion();
  82551. var scaling = BABYLON.Vector3.Zero();
  82552. // Warning on decompose
  82553. var mat = bone.getBaseMatrix();
  82554. if (modifyKey && lastAnimation) {
  82555. mat = lastAnimation.getKeys()[j].value;
  82556. }
  82557. mat.decompose(scaling, rotationQuaternion, translation);
  82558. if (targetPath === "position") {
  82559. translation = value;
  82560. }
  82561. else if (targetPath === "rotationQuaternion") {
  82562. rotationQuaternion = value;
  82563. }
  82564. else {
  82565. scaling = value;
  82566. }
  82567. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  82568. }
  82569. if (!modifyKey) {
  82570. keys.push({
  82571. frame: bufferInput[j],
  82572. value: value
  82573. });
  82574. }
  82575. else if (lastAnimation) {
  82576. lastAnimation.getKeys()[j].value = value;
  82577. }
  82578. }
  82579. // Finish
  82580. if (!modifyKey && babylonAnimation) {
  82581. babylonAnimation.setKeys(keys);
  82582. targetNode.animations.push(babylonAnimation);
  82583. }
  82584. lastAnimation = babylonAnimation;
  82585. gltfRuntime.scene.stopAnimation(targetNode);
  82586. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  82587. }
  82588. }
  82589. };
  82590. /**
  82591. * Returns the bones transformation matrix
  82592. */
  82593. var configureBoneTransformation = function (node) {
  82594. var mat = null;
  82595. if (node.translation || node.rotation || node.scale) {
  82596. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  82597. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  82598. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  82599. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  82600. }
  82601. else {
  82602. mat = BABYLON.Matrix.FromArray(node.matrix);
  82603. }
  82604. return mat;
  82605. };
  82606. /**
  82607. * Returns the parent bone
  82608. */
  82609. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  82610. // Try to find
  82611. for (var i = 0; i < newSkeleton.bones.length; i++) {
  82612. if (newSkeleton.bones[i].name === jointName) {
  82613. return newSkeleton.bones[i];
  82614. }
  82615. }
  82616. // Not found, search in gltf nodes
  82617. var nodes = gltfRuntime.nodes;
  82618. for (var nde in nodes) {
  82619. var node = nodes[nde];
  82620. if (!node.jointName) {
  82621. continue;
  82622. }
  82623. var children = node.children;
  82624. for (var i = 0; i < children.length; i++) {
  82625. var child = gltfRuntime.nodes[children[i]];
  82626. if (!child.jointName) {
  82627. continue;
  82628. }
  82629. if (child.jointName === jointName) {
  82630. var mat = configureBoneTransformation(node);
  82631. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  82632. bone.id = nde;
  82633. return bone;
  82634. }
  82635. }
  82636. }
  82637. return null;
  82638. };
  82639. /**
  82640. * Returns the appropriate root node
  82641. */
  82642. var getNodeToRoot = function (nodesToRoot, id) {
  82643. for (var i = 0; i < nodesToRoot.length; i++) {
  82644. var nodeToRoot = nodesToRoot[i];
  82645. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  82646. var child = nodeToRoot.node.children[j];
  82647. if (child === id) {
  82648. return nodeToRoot.bone;
  82649. }
  82650. }
  82651. }
  82652. return null;
  82653. };
  82654. /**
  82655. * Returns the node with the joint name
  82656. */
  82657. var getJointNode = function (gltfRuntime, jointName) {
  82658. var nodes = gltfRuntime.nodes;
  82659. var node = nodes[jointName];
  82660. if (node) {
  82661. return {
  82662. node: node,
  82663. id: jointName
  82664. };
  82665. }
  82666. for (var nde in nodes) {
  82667. node = nodes[nde];
  82668. if (node.jointName === jointName) {
  82669. return {
  82670. node: node,
  82671. id: nde
  82672. };
  82673. }
  82674. }
  82675. return null;
  82676. };
  82677. /**
  82678. * Checks if a nodes is in joints
  82679. */
  82680. var nodeIsInJoints = function (skins, id) {
  82681. for (var i = 0; i < skins.jointNames.length; i++) {
  82682. if (skins.jointNames[i] === id) {
  82683. return true;
  82684. }
  82685. }
  82686. return false;
  82687. };
  82688. /**
  82689. * Fills the nodes to root for bones and builds hierarchy
  82690. */
  82691. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  82692. // Creates nodes for root
  82693. for (var nde in gltfRuntime.nodes) {
  82694. var node = gltfRuntime.nodes[nde];
  82695. var id = nde;
  82696. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  82697. continue;
  82698. }
  82699. // Create node to root bone
  82700. var mat = configureBoneTransformation(node);
  82701. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  82702. bone.id = id;
  82703. nodesToRoot.push({ bone: bone, node: node, id: id });
  82704. }
  82705. // Parenting
  82706. for (var i = 0; i < nodesToRoot.length; i++) {
  82707. var nodeToRoot = nodesToRoot[i];
  82708. var children = nodeToRoot.node.children;
  82709. for (var j = 0; j < children.length; j++) {
  82710. var child = null;
  82711. for (var k = 0; k < nodesToRoot.length; k++) {
  82712. if (nodesToRoot[k].id === children[j]) {
  82713. child = nodesToRoot[k];
  82714. break;
  82715. }
  82716. }
  82717. if (child) {
  82718. child.bone._parent = nodeToRoot.bone;
  82719. nodeToRoot.bone.children.push(child.bone);
  82720. }
  82721. }
  82722. }
  82723. };
  82724. /**
  82725. * Imports a skeleton
  82726. */
  82727. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  82728. if (!newSkeleton) {
  82729. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  82730. }
  82731. if (!skins.babylonSkeleton) {
  82732. return newSkeleton;
  82733. }
  82734. // Find the root bones
  82735. var nodesToRoot = [];
  82736. var nodesToRootToAdd = [];
  82737. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  82738. newSkeleton.bones = [];
  82739. // Joints
  82740. for (var i = 0; i < skins.jointNames.length; i++) {
  82741. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  82742. if (!jointNode) {
  82743. continue;
  82744. }
  82745. var node = jointNode.node;
  82746. if (!node) {
  82747. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  82748. continue;
  82749. }
  82750. var id = jointNode.id;
  82751. // Optimize, if the bone already exists...
  82752. var existingBone = gltfRuntime.scene.getBoneByID(id);
  82753. if (existingBone) {
  82754. newSkeleton.bones.push(existingBone);
  82755. continue;
  82756. }
  82757. // Search for parent bone
  82758. var foundBone = false;
  82759. var parentBone = null;
  82760. for (var j = 0; j < i; j++) {
  82761. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  82762. if (!jointNode_1) {
  82763. continue;
  82764. }
  82765. var joint = jointNode_1.node;
  82766. if (!joint) {
  82767. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  82768. continue;
  82769. }
  82770. var children = joint.children;
  82771. if (!children) {
  82772. continue;
  82773. }
  82774. foundBone = false;
  82775. for (var k = 0; k < children.length; k++) {
  82776. if (children[k] === id) {
  82777. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  82778. foundBone = true;
  82779. break;
  82780. }
  82781. }
  82782. if (foundBone) {
  82783. break;
  82784. }
  82785. }
  82786. // Create bone
  82787. var mat = configureBoneTransformation(node);
  82788. if (!parentBone && nodesToRoot.length > 0) {
  82789. parentBone = getNodeToRoot(nodesToRoot, id);
  82790. if (parentBone) {
  82791. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  82792. nodesToRootToAdd.push(parentBone);
  82793. }
  82794. }
  82795. }
  82796. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  82797. bone.id = id;
  82798. }
  82799. // Polish
  82800. var bones = newSkeleton.bones;
  82801. newSkeleton.bones = [];
  82802. for (var i = 0; i < skins.jointNames.length; i++) {
  82803. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  82804. if (!jointNode) {
  82805. continue;
  82806. }
  82807. for (var j = 0; j < bones.length; j++) {
  82808. if (bones[j].id === jointNode.id) {
  82809. newSkeleton.bones.push(bones[j]);
  82810. break;
  82811. }
  82812. }
  82813. }
  82814. newSkeleton.prepare();
  82815. // Finish
  82816. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  82817. newSkeleton.bones.push(nodesToRootToAdd[i]);
  82818. }
  82819. return newSkeleton;
  82820. };
  82821. /**
  82822. * Imports a mesh and its geometries
  82823. */
  82824. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  82825. if (!newMesh) {
  82826. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  82827. newMesh.id = id;
  82828. }
  82829. if (!node.babylonNode) {
  82830. return newMesh;
  82831. }
  82832. var subMaterials = [];
  82833. var vertexData = new BABYLON.VertexData();
  82834. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  82835. var verticesStarts = new Array();
  82836. var verticesCounts = new Array();
  82837. var indexStarts = new Array();
  82838. var indexCounts = new Array();
  82839. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  82840. var meshID = meshes[meshIndex];
  82841. var mesh = gltfRuntime.meshes[meshID];
  82842. if (!mesh) {
  82843. continue;
  82844. }
  82845. // Positions, normals and UVs
  82846. for (var i = 0; i < mesh.primitives.length; i++) {
  82847. // Temporary vertex data
  82848. var tempVertexData = new BABYLON.VertexData();
  82849. var primitive = mesh.primitives[i];
  82850. if (primitive.mode !== 4) {
  82851. // continue;
  82852. }
  82853. var attributes = primitive.attributes;
  82854. var accessor = null;
  82855. var buffer = null;
  82856. // Set positions, normal and uvs
  82857. for (var semantic in attributes) {
  82858. // Link accessor and buffer view
  82859. accessor = gltfRuntime.accessors[attributes[semantic]];
  82860. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  82861. if (semantic === "NORMAL") {
  82862. tempVertexData.normals = new Float32Array(buffer.length);
  82863. tempVertexData.normals.set(buffer);
  82864. }
  82865. else if (semantic === "POSITION") {
  82866. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  82867. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  82868. for (var j = 0; j < buffer.length; j += 4) {
  82869. tempVertexData.positions[j] = buffer[j];
  82870. tempVertexData.positions[j + 1] = buffer[j + 1];
  82871. tempVertexData.positions[j + 2] = buffer[j + 2];
  82872. }
  82873. }
  82874. else {
  82875. tempVertexData.positions = new Float32Array(buffer.length);
  82876. tempVertexData.positions.set(buffer);
  82877. }
  82878. verticesCounts.push(tempVertexData.positions.length);
  82879. }
  82880. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  82881. var channel = Number(semantic.split("_")[1]);
  82882. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  82883. var uvs = new Float32Array(buffer.length);
  82884. uvs.set(buffer);
  82885. normalizeUVs(uvs);
  82886. tempVertexData.set(uvs, uvKind);
  82887. }
  82888. else if (semantic === "JOINT") {
  82889. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  82890. tempVertexData.matricesIndices.set(buffer);
  82891. }
  82892. else if (semantic === "WEIGHT") {
  82893. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  82894. tempVertexData.matricesWeights.set(buffer);
  82895. }
  82896. else if (semantic === "COLOR") {
  82897. tempVertexData.colors = new Float32Array(buffer.length);
  82898. tempVertexData.colors.set(buffer);
  82899. }
  82900. }
  82901. // Indices
  82902. accessor = gltfRuntime.accessors[primitive.indices];
  82903. if (accessor) {
  82904. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  82905. tempVertexData.indices = new Int32Array(buffer.length);
  82906. tempVertexData.indices.set(buffer);
  82907. indexCounts.push(tempVertexData.indices.length);
  82908. }
  82909. else {
  82910. // Set indices on the fly
  82911. var indices = [];
  82912. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  82913. indices.push(j);
  82914. }
  82915. tempVertexData.indices = new Int32Array(indices);
  82916. indexCounts.push(tempVertexData.indices.length);
  82917. }
  82918. vertexData.merge(tempVertexData);
  82919. // Sub material
  82920. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  82921. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  82922. // Update vertices start and index start
  82923. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  82924. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  82925. }
  82926. }
  82927. var material;
  82928. if (subMaterials.length > 1) {
  82929. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  82930. material.subMaterials = subMaterials;
  82931. }
  82932. else {
  82933. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  82934. }
  82935. if (subMaterials.length === 1) {
  82936. material = subMaterials[0];
  82937. }
  82938. if (!newMesh.material) {
  82939. newMesh.material = material;
  82940. }
  82941. // Apply geometry
  82942. geometry.setAllVerticesData(vertexData, false);
  82943. newMesh.computeWorldMatrix(true);
  82944. // Apply submeshes
  82945. newMesh.subMeshes = [];
  82946. var index = 0;
  82947. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  82948. var meshID = meshes[meshIndex];
  82949. var mesh = gltfRuntime.meshes[meshID];
  82950. if (!mesh) {
  82951. continue;
  82952. }
  82953. for (var i = 0; i < mesh.primitives.length; i++) {
  82954. if (mesh.primitives[i].mode !== 4) {
  82955. //continue;
  82956. }
  82957. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  82958. index++;
  82959. }
  82960. }
  82961. // Finish
  82962. return newMesh;
  82963. };
  82964. /**
  82965. * Configure node transformation from position, rotation and scaling
  82966. */
  82967. var configureNode = function (newNode, position, rotation, scaling) {
  82968. if (newNode.position) {
  82969. newNode.position = position;
  82970. }
  82971. if (newNode.rotationQuaternion || newNode.rotation) {
  82972. newNode.rotationQuaternion = rotation;
  82973. }
  82974. if (newNode.scaling) {
  82975. newNode.scaling = scaling;
  82976. }
  82977. };
  82978. /**
  82979. * Configures node from transformation matrix
  82980. */
  82981. var configureNodeFromMatrix = function (newNode, node, parent) {
  82982. if (node.matrix) {
  82983. var position = new BABYLON.Vector3(0, 0, 0);
  82984. var rotation = new BABYLON.Quaternion();
  82985. var scaling = new BABYLON.Vector3(0, 0, 0);
  82986. var mat = BABYLON.Matrix.FromArray(node.matrix);
  82987. mat.decompose(scaling, rotation, position);
  82988. configureNode(newNode, position, rotation, scaling);
  82989. }
  82990. else if (node.translation && node.rotation && node.scale) {
  82991. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  82992. }
  82993. newNode.computeWorldMatrix(true);
  82994. };
  82995. /**
  82996. * Imports a node
  82997. */
  82998. var importNode = function (gltfRuntime, node, id, parent) {
  82999. var lastNode = null;
  83000. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  83001. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  83002. return null;
  83003. }
  83004. }
  83005. // Meshes
  83006. if (node.skin) {
  83007. if (node.meshes) {
  83008. var skin = gltfRuntime.skins[node.skin];
  83009. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  83010. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  83011. if (newMesh.skeleton === null) {
  83012. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  83013. if (!skin.babylonSkeleton) {
  83014. skin.babylonSkeleton = newMesh.skeleton;
  83015. }
  83016. }
  83017. lastNode = newMesh;
  83018. }
  83019. }
  83020. else if (node.meshes) {
  83021. /**
  83022. * Improve meshes property
  83023. */
  83024. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  83025. lastNode = newMesh;
  83026. }
  83027. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  83028. var light = gltfRuntime.lights[node.light];
  83029. if (light) {
  83030. if (light.type === "ambient") {
  83031. var ambienLight = light[light.type];
  83032. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83033. hemiLight.name = node.name || "";
  83034. if (ambienLight.color) {
  83035. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  83036. }
  83037. lastNode = hemiLight;
  83038. }
  83039. else if (light.type === "directional") {
  83040. var directionalLight = light[light.type];
  83041. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83042. dirLight.name = node.name || "";
  83043. if (directionalLight.color) {
  83044. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  83045. }
  83046. lastNode = dirLight;
  83047. }
  83048. else if (light.type === "point") {
  83049. var pointLight = light[light.type];
  83050. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83051. ptLight.name = node.name || "";
  83052. if (pointLight.color) {
  83053. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  83054. }
  83055. lastNode = ptLight;
  83056. }
  83057. else if (light.type === "spot") {
  83058. var spotLight = light[light.type];
  83059. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  83060. spLight.name = node.name || "";
  83061. if (spotLight.color) {
  83062. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  83063. }
  83064. if (spotLight.fallOfAngle) {
  83065. spLight.angle = spotLight.fallOfAngle;
  83066. }
  83067. if (spotLight.fallOffExponent) {
  83068. spLight.exponent = spotLight.fallOffExponent;
  83069. }
  83070. lastNode = spLight;
  83071. }
  83072. }
  83073. }
  83074. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  83075. var camera = gltfRuntime.cameras[node.camera];
  83076. if (camera) {
  83077. if (camera.type === "orthographic") {
  83078. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83079. orthoCamera.name = node.name || "";
  83080. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  83081. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  83082. lastNode = orthoCamera;
  83083. }
  83084. else if (camera.type === "perspective") {
  83085. var perspectiveCamera = camera[camera.type];
  83086. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83087. persCamera.name = node.name || "";
  83088. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  83089. if (!perspectiveCamera.aspectRatio) {
  83090. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  83091. }
  83092. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  83093. persCamera.maxZ = perspectiveCamera.zfar;
  83094. persCamera.minZ = perspectiveCamera.znear;
  83095. }
  83096. lastNode = persCamera;
  83097. }
  83098. }
  83099. }
  83100. // Empty node
  83101. if (!node.jointName) {
  83102. if (node.babylonNode) {
  83103. return node.babylonNode;
  83104. }
  83105. else if (lastNode === null) {
  83106. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  83107. node.babylonNode = dummy;
  83108. lastNode = dummy;
  83109. }
  83110. }
  83111. if (lastNode !== null) {
  83112. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  83113. configureNodeFromMatrix(lastNode, node, parent);
  83114. }
  83115. else {
  83116. var translation = node.translation || [0, 0, 0];
  83117. var rotation = node.rotation || [0, 0, 0, 1];
  83118. var scale = node.scale || [1, 1, 1];
  83119. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  83120. }
  83121. lastNode.updateCache(true);
  83122. node.babylonNode = lastNode;
  83123. }
  83124. return lastNode;
  83125. };
  83126. /**
  83127. * Traverses nodes and creates them
  83128. */
  83129. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  83130. if (meshIncluded === void 0) { meshIncluded = false; }
  83131. var node = gltfRuntime.nodes[id];
  83132. var newNode = null;
  83133. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  83134. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  83135. meshIncluded = true;
  83136. }
  83137. else {
  83138. meshIncluded = false;
  83139. }
  83140. }
  83141. else {
  83142. meshIncluded = true;
  83143. }
  83144. if (!node.jointName && meshIncluded) {
  83145. newNode = importNode(gltfRuntime, node, id, parent);
  83146. if (newNode !== null) {
  83147. newNode.id = id;
  83148. newNode.parent = parent;
  83149. }
  83150. }
  83151. if (node.children) {
  83152. for (var i = 0; i < node.children.length; i++) {
  83153. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  83154. }
  83155. }
  83156. };
  83157. /**
  83158. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  83159. */
  83160. var postLoad = function (gltfRuntime) {
  83161. // Nodes
  83162. var currentScene = gltfRuntime.currentScene;
  83163. if (currentScene) {
  83164. for (var i = 0; i < currentScene.nodes.length; i++) {
  83165. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83166. }
  83167. }
  83168. else {
  83169. for (var thing in gltfRuntime.scenes) {
  83170. currentScene = gltfRuntime.scenes[thing];
  83171. for (var i = 0; i < currentScene.nodes.length; i++) {
  83172. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83173. }
  83174. }
  83175. }
  83176. // Set animations
  83177. loadAnimations(gltfRuntime);
  83178. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  83179. var skeleton = gltfRuntime.scene.skeletons[i];
  83180. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  83181. }
  83182. };
  83183. /**
  83184. * onBind shaderrs callback to set uniforms and matrices
  83185. */
  83186. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  83187. var materialValues = material.values || technique.parameters;
  83188. for (var unif in unTreatedUniforms) {
  83189. var uniform = unTreatedUniforms[unif];
  83190. var type = uniform.type;
  83191. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  83192. if (uniform.semantic && !uniform.source && !uniform.node) {
  83193. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  83194. }
  83195. else if (uniform.semantic && (uniform.source || uniform.node)) {
  83196. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  83197. if (source === null) {
  83198. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  83199. }
  83200. if (source === null) {
  83201. continue;
  83202. }
  83203. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  83204. }
  83205. }
  83206. else {
  83207. var value = materialValues[technique.uniforms[unif]];
  83208. if (!value) {
  83209. continue;
  83210. }
  83211. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  83212. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  83213. if (texture === null || texture === undefined) {
  83214. continue;
  83215. }
  83216. shaderMaterial.getEffect().setTexture(unif, texture);
  83217. }
  83218. else {
  83219. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  83220. }
  83221. }
  83222. }
  83223. onSuccess(shaderMaterial);
  83224. };
  83225. /**
  83226. * Prepare uniforms to send the only one time
  83227. * Loads the appropriate textures
  83228. */
  83229. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  83230. var materialValues = material.values || technique.parameters;
  83231. var techniqueUniforms = technique.uniforms;
  83232. /**
  83233. * Prepare values here (not matrices)
  83234. */
  83235. for (var unif in unTreatedUniforms) {
  83236. var uniform = unTreatedUniforms[unif];
  83237. var type = uniform.type;
  83238. var value = materialValues[techniqueUniforms[unif]];
  83239. if (value === undefined) {
  83240. // In case the value is the same for all materials
  83241. value = uniform.value;
  83242. }
  83243. if (!value) {
  83244. continue;
  83245. }
  83246. var onLoadTexture = function (uniformName) {
  83247. return function (texture) {
  83248. if (uniform.value && uniformName) {
  83249. // Static uniform
  83250. shaderMaterial.setTexture(uniformName, texture);
  83251. delete unTreatedUniforms[uniformName];
  83252. }
  83253. };
  83254. };
  83255. // Texture (sampler2D)
  83256. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  83257. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  83258. }
  83259. else {
  83260. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  83261. // Static uniform
  83262. delete unTreatedUniforms[unif];
  83263. }
  83264. }
  83265. }
  83266. };
  83267. /**
  83268. * Shader compilation failed
  83269. */
  83270. var onShaderCompileError = function (program, shaderMaterial, onError) {
  83271. return function (effect, error) {
  83272. shaderMaterial.dispose(true);
  83273. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  83274. };
  83275. };
  83276. /**
  83277. * Shader compilation success
  83278. */
  83279. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  83280. return function (_) {
  83281. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  83282. shaderMaterial.onBind = function (mesh) {
  83283. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  83284. };
  83285. };
  83286. };
  83287. /**
  83288. * Returns the appropriate uniform if already handled by babylon
  83289. */
  83290. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  83291. for (var unif in technique.uniforms) {
  83292. var uniform = technique.uniforms[unif];
  83293. var uniformParameter = technique.parameters[uniform];
  83294. if (tokenizer.currentIdentifier === unif) {
  83295. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  83296. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  83297. if (transformIndex !== -1) {
  83298. delete unTreatedUniforms[unif];
  83299. return babylonTransforms[transformIndex];
  83300. }
  83301. }
  83302. }
  83303. }
  83304. return tokenizer.currentIdentifier;
  83305. };
  83306. /**
  83307. * All shaders loaded. Create materials one by one
  83308. */
  83309. var importMaterials = function (gltfRuntime) {
  83310. // Create materials
  83311. for (var mat in gltfRuntime.materials) {
  83312. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  83313. }
  83314. };
  83315. /**
  83316. * Implementation of the base glTF spec
  83317. */
  83318. var GLTFLoaderBase = /** @class */ (function () {
  83319. function GLTFLoaderBase() {
  83320. }
  83321. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  83322. var gltfRuntime = {
  83323. extensions: {},
  83324. accessors: {},
  83325. buffers: {},
  83326. bufferViews: {},
  83327. meshes: {},
  83328. lights: {},
  83329. cameras: {},
  83330. nodes: {},
  83331. images: {},
  83332. textures: {},
  83333. shaders: {},
  83334. programs: {},
  83335. samplers: {},
  83336. techniques: {},
  83337. materials: {},
  83338. animations: {},
  83339. skins: {},
  83340. extensionsUsed: [],
  83341. scenes: {},
  83342. buffersCount: 0,
  83343. shaderscount: 0,
  83344. scene: scene,
  83345. rootUrl: rootUrl,
  83346. loadedBufferCount: 0,
  83347. loadedBufferViews: {},
  83348. loadedShaderCount: 0,
  83349. importOnlyMeshes: false,
  83350. dummyNodes: []
  83351. };
  83352. // Parse
  83353. if (parsedData.extensions) {
  83354. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  83355. }
  83356. if (parsedData.extensionsUsed) {
  83357. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  83358. }
  83359. if (parsedData.buffers) {
  83360. parseBuffers(parsedData.buffers, gltfRuntime);
  83361. }
  83362. if (parsedData.bufferViews) {
  83363. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  83364. }
  83365. if (parsedData.accessors) {
  83366. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  83367. }
  83368. if (parsedData.meshes) {
  83369. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  83370. }
  83371. if (parsedData.lights) {
  83372. parseObject(parsedData.lights, "lights", gltfRuntime);
  83373. }
  83374. if (parsedData.cameras) {
  83375. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  83376. }
  83377. if (parsedData.nodes) {
  83378. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  83379. }
  83380. if (parsedData.images) {
  83381. parseObject(parsedData.images, "images", gltfRuntime);
  83382. }
  83383. if (parsedData.textures) {
  83384. parseObject(parsedData.textures, "textures", gltfRuntime);
  83385. }
  83386. if (parsedData.shaders) {
  83387. parseShaders(parsedData.shaders, gltfRuntime);
  83388. }
  83389. if (parsedData.programs) {
  83390. parseObject(parsedData.programs, "programs", gltfRuntime);
  83391. }
  83392. if (parsedData.samplers) {
  83393. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  83394. }
  83395. if (parsedData.techniques) {
  83396. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  83397. }
  83398. if (parsedData.materials) {
  83399. parseObject(parsedData.materials, "materials", gltfRuntime);
  83400. }
  83401. if (parsedData.animations) {
  83402. parseObject(parsedData.animations, "animations", gltfRuntime);
  83403. }
  83404. if (parsedData.skins) {
  83405. parseObject(parsedData.skins, "skins", gltfRuntime);
  83406. }
  83407. if (parsedData.scenes) {
  83408. gltfRuntime.scenes = parsedData.scenes;
  83409. }
  83410. if (parsedData.scene && parsedData.scenes) {
  83411. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  83412. }
  83413. return gltfRuntime;
  83414. };
  83415. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  83416. var buffer = gltfRuntime.buffers[id];
  83417. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  83418. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  83419. }
  83420. else {
  83421. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  83422. if (request) {
  83423. onError(request.status + " " + request.statusText);
  83424. }
  83425. });
  83426. }
  83427. };
  83428. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  83429. var texture = gltfRuntime.textures[id];
  83430. if (!texture || !texture.source) {
  83431. onError("");
  83432. return;
  83433. }
  83434. if (texture.babylonTexture) {
  83435. onSuccess(null);
  83436. return;
  83437. }
  83438. var source = gltfRuntime.images[texture.source];
  83439. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  83440. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  83441. }
  83442. else {
  83443. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  83444. if (request) {
  83445. onError(request.status + " " + request.statusText);
  83446. }
  83447. });
  83448. }
  83449. };
  83450. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  83451. var texture = gltfRuntime.textures[id];
  83452. if (texture.babylonTexture) {
  83453. onSuccess(texture.babylonTexture);
  83454. return;
  83455. }
  83456. var sampler = gltfRuntime.samplers[texture.sampler];
  83457. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  83458. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  83459. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  83460. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  83461. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  83462. var blob = new Blob([buffer]);
  83463. var blobURL = URL.createObjectURL(blob);
  83464. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  83465. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  83466. if (sampler.wrapS !== undefined) {
  83467. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  83468. }
  83469. if (sampler.wrapT !== undefined) {
  83470. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  83471. }
  83472. newTexture.name = id;
  83473. texture.babylonTexture = newTexture;
  83474. onSuccess(newTexture);
  83475. };
  83476. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  83477. var shader = gltfRuntime.shaders[id];
  83478. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  83479. var shaderString = atob(shader.uri.split(",")[1]);
  83480. onSuccess(shaderString);
  83481. }
  83482. else {
  83483. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  83484. if (request) {
  83485. onError(request.status + " " + request.statusText);
  83486. }
  83487. });
  83488. }
  83489. };
  83490. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  83491. var material = gltfRuntime.materials[id];
  83492. if (!material.technique) {
  83493. if (onError) {
  83494. onError("No technique found.");
  83495. }
  83496. return;
  83497. }
  83498. var technique = gltfRuntime.techniques[material.technique];
  83499. if (!technique) {
  83500. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  83501. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  83502. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  83503. onSuccess(defaultMaterial);
  83504. return;
  83505. }
  83506. var program = gltfRuntime.programs[technique.program];
  83507. var states = technique.states;
  83508. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  83509. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  83510. var newVertexShader = "";
  83511. var newPixelShader = "";
  83512. var vertexTokenizer = new Tokenizer(vertexShader);
  83513. var pixelTokenizer = new Tokenizer(pixelShader);
  83514. var unTreatedUniforms = {};
  83515. var uniforms = [];
  83516. var attributes = [];
  83517. var samplers = [];
  83518. // Fill uniform, sampler2D and attributes
  83519. for (var unif in technique.uniforms) {
  83520. var uniform = technique.uniforms[unif];
  83521. var uniformParameter = technique.parameters[uniform];
  83522. unTreatedUniforms[unif] = uniformParameter;
  83523. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  83524. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  83525. if (transformIndex !== -1) {
  83526. uniforms.push(babylonTransforms[transformIndex]);
  83527. delete unTreatedUniforms[unif];
  83528. }
  83529. else {
  83530. uniforms.push(unif);
  83531. }
  83532. }
  83533. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  83534. samplers.push(unif);
  83535. }
  83536. else {
  83537. uniforms.push(unif);
  83538. }
  83539. }
  83540. for (var attr in technique.attributes) {
  83541. var attribute = technique.attributes[attr];
  83542. var attributeParameter = technique.parameters[attribute];
  83543. if (attributeParameter.semantic) {
  83544. attributes.push(getAttribute(attributeParameter));
  83545. }
  83546. }
  83547. // Configure vertex shader
  83548. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  83549. var tokenType = vertexTokenizer.currentToken;
  83550. if (tokenType !== ETokenType.IDENTIFIER) {
  83551. newVertexShader += vertexTokenizer.currentString;
  83552. continue;
  83553. }
  83554. var foundAttribute = false;
  83555. for (var attr in technique.attributes) {
  83556. var attribute = technique.attributes[attr];
  83557. var attributeParameter = technique.parameters[attribute];
  83558. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  83559. newVertexShader += getAttribute(attributeParameter);
  83560. foundAttribute = true;
  83561. break;
  83562. }
  83563. }
  83564. if (foundAttribute) {
  83565. continue;
  83566. }
  83567. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  83568. }
  83569. // Configure pixel shader
  83570. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  83571. var tokenType = pixelTokenizer.currentToken;
  83572. if (tokenType !== ETokenType.IDENTIFIER) {
  83573. newPixelShader += pixelTokenizer.currentString;
  83574. continue;
  83575. }
  83576. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  83577. }
  83578. // Create shader material
  83579. var shaderPath = {
  83580. vertex: program.vertexShader + id,
  83581. fragment: program.fragmentShader + id
  83582. };
  83583. var options = {
  83584. attributes: attributes,
  83585. uniforms: uniforms,
  83586. samplers: samplers,
  83587. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  83588. };
  83589. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  83590. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  83591. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  83592. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  83593. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  83594. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  83595. if (states && states.functions) {
  83596. var functions = states.functions;
  83597. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  83598. shaderMaterial.backFaceCulling = false;
  83599. }
  83600. var blendFunc = functions.blendFuncSeparate;
  83601. if (blendFunc) {
  83602. 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) {
  83603. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  83604. }
  83605. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  83606. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83607. }
  83608. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  83609. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  83610. }
  83611. 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) {
  83612. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  83613. }
  83614. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  83615. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  83616. }
  83617. 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) {
  83618. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  83619. }
  83620. }
  83621. }
  83622. };
  83623. return GLTFLoaderBase;
  83624. }());
  83625. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  83626. /**
  83627. * glTF V1 Loader
  83628. */
  83629. var GLTFLoader = /** @class */ (function () {
  83630. function GLTFLoader() {
  83631. // #region Stubs for IGLTFLoader interface
  83632. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  83633. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  83634. this.compileMaterials = false;
  83635. this.useClipPlane = false;
  83636. this.compileShadowGenerators = false;
  83637. this.onDisposeObservable = new BABYLON.Observable();
  83638. this.onMeshLoadedObservable = new BABYLON.Observable();
  83639. this.onTextureLoadedObservable = new BABYLON.Observable();
  83640. this.onMaterialLoadedObservable = new BABYLON.Observable();
  83641. this.onCompleteObservable = new BABYLON.Observable();
  83642. }
  83643. GLTFLoader.RegisterExtension = function (extension) {
  83644. if (GLTFLoader.Extensions[extension.name]) {
  83645. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  83646. return;
  83647. }
  83648. GLTFLoader.Extensions[extension.name] = extension;
  83649. };
  83650. GLTFLoader.prototype.dispose = function () { };
  83651. // #endregion
  83652. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  83653. var _this = this;
  83654. scene.useRightHandedSystem = true;
  83655. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  83656. gltfRuntime.importOnlyMeshes = true;
  83657. if (meshesNames === "") {
  83658. gltfRuntime.importMeshesNames = [];
  83659. }
  83660. else if (typeof meshesNames === "string") {
  83661. gltfRuntime.importMeshesNames = [meshesNames];
  83662. }
  83663. else if (meshesNames && !(meshesNames instanceof Array)) {
  83664. gltfRuntime.importMeshesNames = [meshesNames];
  83665. }
  83666. else {
  83667. gltfRuntime.importMeshesNames = [];
  83668. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  83669. }
  83670. // Create nodes
  83671. _this._createNodes(gltfRuntime);
  83672. var meshes = new Array();
  83673. var skeletons = new Array();
  83674. // Fill arrays of meshes and skeletons
  83675. for (var nde in gltfRuntime.nodes) {
  83676. var node = gltfRuntime.nodes[nde];
  83677. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  83678. meshes.push(node.babylonNode);
  83679. }
  83680. }
  83681. for (var skl in gltfRuntime.skins) {
  83682. var skin = gltfRuntime.skins[skl];
  83683. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  83684. skeletons.push(skin.babylonSkeleton);
  83685. }
  83686. }
  83687. // Load buffers, shaders, materials, etc.
  83688. _this._loadBuffersAsync(gltfRuntime, function () {
  83689. _this._loadShadersAsync(gltfRuntime, function () {
  83690. importMaterials(gltfRuntime);
  83691. postLoad(gltfRuntime);
  83692. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  83693. onSuccess(meshes, [], skeletons);
  83694. }
  83695. });
  83696. }, onProgress);
  83697. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  83698. onSuccess(meshes, [], skeletons);
  83699. }
  83700. }, onError);
  83701. return true;
  83702. };
  83703. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  83704. var _this = this;
  83705. scene.useRightHandedSystem = true;
  83706. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  83707. // Load runtime extensios
  83708. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  83709. // Create nodes
  83710. _this._createNodes(gltfRuntime);
  83711. // Load buffers, shaders, materials, etc.
  83712. _this._loadBuffersAsync(gltfRuntime, function () {
  83713. _this._loadShadersAsync(gltfRuntime, function () {
  83714. importMaterials(gltfRuntime);
  83715. postLoad(gltfRuntime);
  83716. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  83717. onSuccess();
  83718. }
  83719. });
  83720. });
  83721. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  83722. onSuccess();
  83723. }
  83724. }, onError);
  83725. }, onError);
  83726. };
  83727. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  83728. var hasShaders = false;
  83729. var processShader = function (sha, shader) {
  83730. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  83731. gltfRuntime.loadedShaderCount++;
  83732. if (shaderString) {
  83733. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  83734. }
  83735. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  83736. onload();
  83737. }
  83738. }, function () {
  83739. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  83740. });
  83741. };
  83742. for (var sha in gltfRuntime.shaders) {
  83743. hasShaders = true;
  83744. var shader = gltfRuntime.shaders[sha];
  83745. if (shader) {
  83746. processShader.bind(this, sha, shader)();
  83747. }
  83748. else {
  83749. BABYLON.Tools.Error("No shader named: " + sha);
  83750. }
  83751. }
  83752. if (!hasShaders) {
  83753. onload();
  83754. }
  83755. };
  83756. ;
  83757. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  83758. var hasBuffers = false;
  83759. var processBuffer = function (buf, buffer) {
  83760. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  83761. gltfRuntime.loadedBufferCount++;
  83762. if (bufferView) {
  83763. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  83764. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  83765. }
  83766. gltfRuntime.loadedBufferViews[buf] = bufferView;
  83767. }
  83768. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  83769. onLoad();
  83770. }
  83771. }, function () {
  83772. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  83773. });
  83774. };
  83775. for (var buf in gltfRuntime.buffers) {
  83776. hasBuffers = true;
  83777. var buffer = gltfRuntime.buffers[buf];
  83778. if (buffer) {
  83779. processBuffer.bind(this, buf, buffer)();
  83780. }
  83781. else {
  83782. BABYLON.Tools.Error("No buffer named: " + buf);
  83783. }
  83784. }
  83785. if (!hasBuffers) {
  83786. onLoad();
  83787. }
  83788. };
  83789. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  83790. var currentScene = gltfRuntime.currentScene;
  83791. if (currentScene) {
  83792. // Only one scene even if multiple scenes are defined
  83793. for (var i = 0; i < currentScene.nodes.length; i++) {
  83794. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83795. }
  83796. }
  83797. else {
  83798. // Load all scenes
  83799. for (var thing in gltfRuntime.scenes) {
  83800. currentScene = gltfRuntime.scenes[thing];
  83801. for (var i = 0; i < currentScene.nodes.length; i++) {
  83802. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83803. }
  83804. }
  83805. }
  83806. };
  83807. GLTFLoader.Extensions = {};
  83808. return GLTFLoader;
  83809. }());
  83810. GLTF1.GLTFLoader = GLTFLoader;
  83811. ;
  83812. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  83813. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  83814. })(BABYLON || (BABYLON = {}));
  83815. //# sourceMappingURL=babylon.glTFLoader.js.map
  83816. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  83817. var BABYLON;
  83818. (function (BABYLON) {
  83819. var GLTF1;
  83820. (function (GLTF1) {
  83821. /**
  83822. * Utils functions for GLTF
  83823. */
  83824. var GLTFUtils = /** @class */ (function () {
  83825. function GLTFUtils() {
  83826. }
  83827. /**
  83828. * Sets the given "parameter" matrix
  83829. * @param scene: the {BABYLON.Scene} object
  83830. * @param source: the source node where to pick the matrix
  83831. * @param parameter: the GLTF technique parameter
  83832. * @param uniformName: the name of the shader's uniform
  83833. * @param shaderMaterial: the shader material
  83834. */
  83835. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  83836. var mat = null;
  83837. if (parameter.semantic === "MODEL") {
  83838. mat = source.getWorldMatrix();
  83839. }
  83840. else if (parameter.semantic === "PROJECTION") {
  83841. mat = scene.getProjectionMatrix();
  83842. }
  83843. else if (parameter.semantic === "VIEW") {
  83844. mat = scene.getViewMatrix();
  83845. }
  83846. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  83847. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  83848. }
  83849. else if (parameter.semantic === "MODELVIEW") {
  83850. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  83851. }
  83852. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  83853. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  83854. }
  83855. else if (parameter.semantic === "MODELINVERSE") {
  83856. mat = source.getWorldMatrix().invert();
  83857. }
  83858. else if (parameter.semantic === "VIEWINVERSE") {
  83859. mat = scene.getViewMatrix().invert();
  83860. }
  83861. else if (parameter.semantic === "PROJECTIONINVERSE") {
  83862. mat = scene.getProjectionMatrix().invert();
  83863. }
  83864. else if (parameter.semantic === "MODELVIEWINVERSE") {
  83865. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  83866. }
  83867. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  83868. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  83869. }
  83870. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  83871. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  83872. }
  83873. else {
  83874. debugger;
  83875. }
  83876. if (mat) {
  83877. switch (parameter.type) {
  83878. case GLTF1.EParameterType.FLOAT_MAT2:
  83879. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  83880. break;
  83881. case GLTF1.EParameterType.FLOAT_MAT3:
  83882. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  83883. break;
  83884. case GLTF1.EParameterType.FLOAT_MAT4:
  83885. shaderMaterial.setMatrix(uniformName, mat);
  83886. break;
  83887. default: break;
  83888. }
  83889. }
  83890. };
  83891. /**
  83892. * Sets the given "parameter" matrix
  83893. * @param shaderMaterial: the shader material
  83894. * @param uniform: the name of the shader's uniform
  83895. * @param value: the value of the uniform
  83896. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  83897. */
  83898. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  83899. switch (type) {
  83900. case GLTF1.EParameterType.FLOAT:
  83901. shaderMaterial.setFloat(uniform, value);
  83902. return true;
  83903. case GLTF1.EParameterType.FLOAT_VEC2:
  83904. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  83905. return true;
  83906. case GLTF1.EParameterType.FLOAT_VEC3:
  83907. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  83908. return true;
  83909. case GLTF1.EParameterType.FLOAT_VEC4:
  83910. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  83911. return true;
  83912. default: return false;
  83913. }
  83914. };
  83915. /**
  83916. * If the uri is a base64 string
  83917. * @param uri: the uri to test
  83918. */
  83919. GLTFUtils.IsBase64 = function (uri) {
  83920. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  83921. };
  83922. /**
  83923. * Decode the base64 uri
  83924. * @param uri: the uri to decode
  83925. */
  83926. GLTFUtils.DecodeBase64 = function (uri) {
  83927. var decodedString = atob(uri.split(",")[1]);
  83928. var bufferLength = decodedString.length;
  83929. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  83930. for (var i = 0; i < bufferLength; i++) {
  83931. bufferView[i] = decodedString.charCodeAt(i);
  83932. }
  83933. return bufferView.buffer;
  83934. };
  83935. /**
  83936. * Returns the wrap mode of the texture
  83937. * @param mode: the mode value
  83938. */
  83939. GLTFUtils.GetWrapMode = function (mode) {
  83940. switch (mode) {
  83941. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  83942. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  83943. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  83944. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  83945. }
  83946. };
  83947. /**
  83948. * Returns the byte stride giving an accessor
  83949. * @param accessor: the GLTF accessor objet
  83950. */
  83951. GLTFUtils.GetByteStrideFromType = function (accessor) {
  83952. // Needs this function since "byteStride" isn't requiered in glTF format
  83953. var type = accessor.type;
  83954. switch (type) {
  83955. case "VEC2": return 2;
  83956. case "VEC3": return 3;
  83957. case "VEC4": return 4;
  83958. case "MAT2": return 4;
  83959. case "MAT3": return 9;
  83960. case "MAT4": return 16;
  83961. default: return 1;
  83962. }
  83963. };
  83964. /**
  83965. * Returns the texture filter mode giving a mode value
  83966. * @param mode: the filter mode value
  83967. */
  83968. GLTFUtils.GetTextureFilterMode = function (mode) {
  83969. switch (mode) {
  83970. case GLTF1.ETextureFilterType.LINEAR:
  83971. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  83972. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  83973. case GLTF1.ETextureFilterType.NEAREST:
  83974. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  83975. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  83976. }
  83977. };
  83978. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  83979. var byteOffset = bufferView.byteOffset + byteOffset;
  83980. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  83981. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  83982. throw new Error("Buffer access is out of range");
  83983. }
  83984. var buffer = loadedBufferView.buffer;
  83985. byteOffset += loadedBufferView.byteOffset;
  83986. switch (componentType) {
  83987. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  83988. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  83989. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  83990. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  83991. default: return new Float32Array(buffer, byteOffset, byteLength);
  83992. }
  83993. };
  83994. /**
  83995. * Returns a buffer from its accessor
  83996. * @param gltfRuntime: the GLTF runtime
  83997. * @param accessor: the GLTF accessor
  83998. */
  83999. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  84000. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  84001. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  84002. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  84003. };
  84004. /**
  84005. * Decodes a buffer view into a string
  84006. * @param view: the buffer view
  84007. */
  84008. GLTFUtils.DecodeBufferToText = function (view) {
  84009. var result = "";
  84010. var length = view.byteLength;
  84011. for (var i = 0; i < length; ++i) {
  84012. result += String.fromCharCode(view[i]);
  84013. }
  84014. return result;
  84015. };
  84016. /**
  84017. * Returns the default material of gltf. Related to
  84018. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  84019. * @param scene: the Babylon.js scene
  84020. */
  84021. GLTFUtils.GetDefaultMaterial = function (scene) {
  84022. if (!GLTFUtils._DefaultMaterial) {
  84023. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  84024. "precision highp float;",
  84025. "",
  84026. "uniform mat4 worldView;",
  84027. "uniform mat4 projection;",
  84028. "",
  84029. "attribute vec3 position;",
  84030. "",
  84031. "void main(void)",
  84032. "{",
  84033. " gl_Position = projection * worldView * vec4(position, 1.0);",
  84034. "}"
  84035. ].join("\n");
  84036. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  84037. "precision highp float;",
  84038. "",
  84039. "uniform vec4 u_emission;",
  84040. "",
  84041. "void main(void)",
  84042. "{",
  84043. " gl_FragColor = u_emission;",
  84044. "}"
  84045. ].join("\n");
  84046. var shaderPath = {
  84047. vertex: "GLTFDefaultMaterial",
  84048. fragment: "GLTFDefaultMaterial"
  84049. };
  84050. var options = {
  84051. attributes: ["position"],
  84052. uniforms: ["worldView", "projection", "u_emission"],
  84053. samplers: new Array(),
  84054. needAlphaBlending: false
  84055. };
  84056. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  84057. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  84058. }
  84059. return GLTFUtils._DefaultMaterial;
  84060. };
  84061. // The GLTF default material
  84062. GLTFUtils._DefaultMaterial = null;
  84063. return GLTFUtils;
  84064. }());
  84065. GLTF1.GLTFUtils = GLTFUtils;
  84066. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84067. })(BABYLON || (BABYLON = {}));
  84068. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  84069. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84070. var BABYLON;
  84071. (function (BABYLON) {
  84072. var GLTF1;
  84073. (function (GLTF1) {
  84074. var GLTFLoaderExtension = /** @class */ (function () {
  84075. function GLTFLoaderExtension(name) {
  84076. this._name = name;
  84077. }
  84078. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  84079. get: function () {
  84080. return this._name;
  84081. },
  84082. enumerable: true,
  84083. configurable: true
  84084. });
  84085. /**
  84086. * Defines an override for loading the runtime
  84087. * Return true to stop further extensions from loading the runtime
  84088. */
  84089. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  84090. return false;
  84091. };
  84092. /**
  84093. * Defines an onverride for creating gltf runtime
  84094. * Return true to stop further extensions from creating the runtime
  84095. */
  84096. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  84097. return false;
  84098. };
  84099. /**
  84100. * Defines an override for loading buffers
  84101. * Return true to stop further extensions from loading this buffer
  84102. */
  84103. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  84104. return false;
  84105. };
  84106. /**
  84107. * Defines an override for loading texture buffers
  84108. * Return true to stop further extensions from loading this texture data
  84109. */
  84110. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84111. return false;
  84112. };
  84113. /**
  84114. * Defines an override for creating textures
  84115. * Return true to stop further extensions from loading this texture
  84116. */
  84117. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  84118. return false;
  84119. };
  84120. /**
  84121. * Defines an override for loading shader strings
  84122. * Return true to stop further extensions from loading this shader data
  84123. */
  84124. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  84125. return false;
  84126. };
  84127. /**
  84128. * Defines an override for loading materials
  84129. * Return true to stop further extensions from loading this material
  84130. */
  84131. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  84132. return false;
  84133. };
  84134. // ---------
  84135. // Utilities
  84136. // ---------
  84137. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  84138. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84139. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  84140. }, function () {
  84141. setTimeout(function () {
  84142. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  84143. });
  84144. });
  84145. };
  84146. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  84147. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84148. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  84149. }, function () {
  84150. setTimeout(function () {
  84151. onSuccess();
  84152. });
  84153. });
  84154. };
  84155. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  84156. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84157. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  84158. }, function () {
  84159. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  84160. });
  84161. };
  84162. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  84163. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  84164. };
  84165. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  84166. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84167. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  84168. }, function () {
  84169. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  84170. });
  84171. };
  84172. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  84173. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84174. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  84175. }, function () {
  84176. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  84177. });
  84178. };
  84179. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84180. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84181. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  84182. }, function () {
  84183. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  84184. });
  84185. };
  84186. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  84187. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84188. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  84189. }, function () {
  84190. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  84191. });
  84192. };
  84193. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  84194. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  84195. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  84196. if (func(loaderExtension)) {
  84197. return;
  84198. }
  84199. }
  84200. defaultFunc();
  84201. };
  84202. return GLTFLoaderExtension;
  84203. }());
  84204. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  84205. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84206. })(BABYLON || (BABYLON = {}));
  84207. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  84208. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84209. var BABYLON;
  84210. (function (BABYLON) {
  84211. var GLTF1;
  84212. (function (GLTF1) {
  84213. var BinaryExtensionBufferName = "binary_glTF";
  84214. ;
  84215. ;
  84216. var GLTFBinaryExtension = /** @class */ (function (_super) {
  84217. __extends(GLTFBinaryExtension, _super);
  84218. function GLTFBinaryExtension() {
  84219. return _super.call(this, "KHR_binary_glTF") || this;
  84220. }
  84221. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  84222. var extensionsUsed = data.json.extensionsUsed;
  84223. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  84224. return false;
  84225. }
  84226. this._bin = data.bin;
  84227. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  84228. return true;
  84229. };
  84230. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84231. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  84232. return false;
  84233. }
  84234. if (id !== BinaryExtensionBufferName) {
  84235. return false;
  84236. }
  84237. onSuccess(this._bin);
  84238. return true;
  84239. };
  84240. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84241. var texture = gltfRuntime.textures[id];
  84242. var source = gltfRuntime.images[texture.source];
  84243. if (!source.extensions || !(this.name in source.extensions)) {
  84244. return false;
  84245. }
  84246. var sourceExt = source.extensions[this.name];
  84247. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  84248. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  84249. onSuccess(buffer);
  84250. return true;
  84251. };
  84252. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  84253. var shader = gltfRuntime.shaders[id];
  84254. if (!shader.extensions || !(this.name in shader.extensions)) {
  84255. return false;
  84256. }
  84257. var binaryExtensionShader = shader.extensions[this.name];
  84258. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  84259. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  84260. setTimeout(function () {
  84261. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  84262. onSuccess(shaderString);
  84263. });
  84264. return true;
  84265. };
  84266. return GLTFBinaryExtension;
  84267. }(GLTF1.GLTFLoaderExtension));
  84268. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  84269. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  84270. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84271. })(BABYLON || (BABYLON = {}));
  84272. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  84273. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84274. var BABYLON;
  84275. (function (BABYLON) {
  84276. var GLTF1;
  84277. (function (GLTF1) {
  84278. ;
  84279. ;
  84280. ;
  84281. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  84282. __extends(GLTFMaterialsCommonExtension, _super);
  84283. function GLTFMaterialsCommonExtension() {
  84284. return _super.call(this, "KHR_materials_common") || this;
  84285. }
  84286. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  84287. if (!gltfRuntime.extensions)
  84288. return false;
  84289. var extension = gltfRuntime.extensions[this.name];
  84290. if (!extension)
  84291. return false;
  84292. // Create lights
  84293. var lights = extension.lights;
  84294. if (lights) {
  84295. for (var thing in lights) {
  84296. var light = lights[thing];
  84297. switch (light.type) {
  84298. case "ambient":
  84299. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  84300. var ambient = light.ambient;
  84301. if (ambient) {
  84302. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  84303. }
  84304. break;
  84305. case "point":
  84306. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  84307. var point = light.point;
  84308. if (point) {
  84309. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  84310. }
  84311. break;
  84312. case "directional":
  84313. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  84314. var directional = light.directional;
  84315. if (directional) {
  84316. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  84317. }
  84318. break;
  84319. case "spot":
  84320. var spot = light.spot;
  84321. if (spot) {
  84322. 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);
  84323. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  84324. }
  84325. break;
  84326. default:
  84327. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  84328. break;
  84329. }
  84330. }
  84331. }
  84332. return false;
  84333. };
  84334. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  84335. var material = gltfRuntime.materials[id];
  84336. if (!material || !material.extensions)
  84337. return false;
  84338. var extension = material.extensions[this.name];
  84339. if (!extension)
  84340. return false;
  84341. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  84342. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  84343. if (extension.technique === "CONSTANT") {
  84344. standardMaterial.disableLighting = true;
  84345. }
  84346. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  84347. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  84348. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  84349. // Ambient
  84350. if (typeof extension.values.ambient === "string") {
  84351. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  84352. }
  84353. else {
  84354. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  84355. }
  84356. // Diffuse
  84357. if (typeof extension.values.diffuse === "string") {
  84358. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  84359. }
  84360. else {
  84361. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  84362. }
  84363. // Emission
  84364. if (typeof extension.values.emission === "string") {
  84365. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  84366. }
  84367. else {
  84368. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  84369. }
  84370. // Specular
  84371. if (typeof extension.values.specular === "string") {
  84372. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  84373. }
  84374. else {
  84375. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  84376. }
  84377. return true;
  84378. };
  84379. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  84380. // Create buffer from texture url
  84381. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  84382. // Create texture from buffer
  84383. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  84384. }, onError);
  84385. };
  84386. return GLTFMaterialsCommonExtension;
  84387. }(GLTF1.GLTFLoaderExtension));
  84388. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  84389. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  84390. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84391. })(BABYLON || (BABYLON = {}));
  84392. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  84393. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84394. var BABYLON;
  84395. (function (BABYLON) {
  84396. var GLTF2;
  84397. (function (GLTF2) {
  84398. /**
  84399. * Enums
  84400. */
  84401. var EComponentType;
  84402. (function (EComponentType) {
  84403. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  84404. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  84405. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  84406. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  84407. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  84408. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  84409. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  84410. var EMeshPrimitiveMode;
  84411. (function (EMeshPrimitiveMode) {
  84412. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  84413. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  84414. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  84415. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  84416. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  84417. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  84418. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  84419. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  84420. var ETextureMagFilter;
  84421. (function (ETextureMagFilter) {
  84422. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  84423. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  84424. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  84425. var ETextureMinFilter;
  84426. (function (ETextureMinFilter) {
  84427. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  84428. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  84429. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  84430. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  84431. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  84432. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  84433. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  84434. var ETextureWrapMode;
  84435. (function (ETextureWrapMode) {
  84436. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  84437. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  84438. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  84439. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  84440. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  84441. })(BABYLON || (BABYLON = {}));
  84442. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  84443. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84444. var BABYLON;
  84445. (function (BABYLON) {
  84446. var GLTF2;
  84447. (function (GLTF2) {
  84448. var GLTFLoaderTracker = /** @class */ (function () {
  84449. function GLTFLoaderTracker(onComplete) {
  84450. this._pendingCount = 0;
  84451. this._callback = onComplete;
  84452. }
  84453. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  84454. this._pendingCount++;
  84455. };
  84456. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  84457. if (--this._pendingCount === 0) {
  84458. this._callback();
  84459. }
  84460. };
  84461. return GLTFLoaderTracker;
  84462. }());
  84463. var GLTFLoader = /** @class */ (function () {
  84464. function GLTFLoader() {
  84465. this._disposed = false;
  84466. this._defaultSampler = {};
  84467. this._renderReady = false;
  84468. this._requests = new Array();
  84469. this._renderReadyObservable = new BABYLON.Observable();
  84470. // Count of pending work that needs to complete before the asset is rendered.
  84471. this._renderPendingCount = 0;
  84472. // Count of pending work that needs to complete before the loader is disposed.
  84473. this._loaderPendingCount = 0;
  84474. this._loaderTrackers = new Array();
  84475. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  84476. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  84477. this.compileMaterials = false;
  84478. this.useClipPlane = false;
  84479. this.compileShadowGenerators = false;
  84480. this.onDisposeObservable = new BABYLON.Observable();
  84481. this.onMeshLoadedObservable = new BABYLON.Observable();
  84482. this.onTextureLoadedObservable = new BABYLON.Observable();
  84483. this.onMaterialLoadedObservable = new BABYLON.Observable();
  84484. this.onCompleteObservable = new BABYLON.Observable();
  84485. }
  84486. GLTFLoader.RegisterExtension = function (extension) {
  84487. if (GLTFLoader.Extensions[extension.name]) {
  84488. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  84489. return;
  84490. }
  84491. GLTFLoader.Extensions[extension.name] = extension;
  84492. // Keep the order of registration so that extensions registered first are called first.
  84493. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  84494. };
  84495. GLTFLoader.prototype.dispose = function () {
  84496. if (this._disposed) {
  84497. return;
  84498. }
  84499. this._disposed = true;
  84500. this._abortRequests();
  84501. this._releaseResources();
  84502. this.onDisposeObservable.notifyObservers(this);
  84503. };
  84504. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  84505. var _this = this;
  84506. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  84507. if (onSuccess) {
  84508. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  84509. }
  84510. }, onProgress, onError);
  84511. };
  84512. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  84513. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  84514. };
  84515. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  84516. var _this = this;
  84517. this._babylonScene = scene;
  84518. this._rootUrl = rootUrl;
  84519. this._successCallback = onSuccess;
  84520. this._progressCallback = onProgress;
  84521. this._errorCallback = onError;
  84522. this._tryCatchOnError(function () {
  84523. _this._loadData(data);
  84524. _this._addPendingData(_this);
  84525. _this._loadDefaultScene(nodeNames);
  84526. _this._loadAnimations();
  84527. _this._removePendingData(_this);
  84528. });
  84529. };
  84530. GLTFLoader.prototype._onProgress = function () {
  84531. if (!this._progressCallback) {
  84532. return;
  84533. }
  84534. var lengthComputable = true;
  84535. var loaded = 0;
  84536. var total = 0;
  84537. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  84538. var request = _a[_i];
  84539. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  84540. return;
  84541. }
  84542. lengthComputable = lengthComputable && request._lengthComputable;
  84543. loaded += request._loaded;
  84544. total += request._total;
  84545. }
  84546. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  84547. };
  84548. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  84549. if (this._renderReady) {
  84550. func();
  84551. }
  84552. else {
  84553. this._renderReadyObservable.add(func);
  84554. }
  84555. };
  84556. GLTFLoader.prototype._onRenderReady = function () {
  84557. this._rootNode.babylonMesh.setEnabled(true);
  84558. this._startAnimations();
  84559. if (this._successCallback) {
  84560. this._successCallback();
  84561. }
  84562. this._renderReadyObservable.notifyObservers(this);
  84563. };
  84564. GLTFLoader.prototype._onComplete = function () {
  84565. this._abortRequests();
  84566. this._releaseResources();
  84567. this.onCompleteObservable.notifyObservers(this);
  84568. };
  84569. GLTFLoader.prototype._loadData = function (data) {
  84570. this._gltf = data.json;
  84571. // Assign the index of each object for convinience.
  84572. GLTFLoader._AssignIndices(this._gltf.accessors);
  84573. GLTFLoader._AssignIndices(this._gltf.animations);
  84574. GLTFLoader._AssignIndices(this._gltf.buffers);
  84575. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  84576. GLTFLoader._AssignIndices(this._gltf.images);
  84577. GLTFLoader._AssignIndices(this._gltf.materials);
  84578. GLTFLoader._AssignIndices(this._gltf.meshes);
  84579. GLTFLoader._AssignIndices(this._gltf.nodes);
  84580. GLTFLoader._AssignIndices(this._gltf.samplers);
  84581. GLTFLoader._AssignIndices(this._gltf.scenes);
  84582. GLTFLoader._AssignIndices(this._gltf.skins);
  84583. GLTFLoader._AssignIndices(this._gltf.textures);
  84584. if (data.bin) {
  84585. var buffers = this._gltf.buffers;
  84586. if (buffers && buffers[0] && !buffers[0].uri) {
  84587. var binaryBuffer = buffers[0];
  84588. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  84589. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  84590. }
  84591. binaryBuffer.loadedData = data.bin;
  84592. }
  84593. else {
  84594. BABYLON.Tools.Warn("Unexpected BIN chunk");
  84595. }
  84596. }
  84597. };
  84598. GLTFLoader.prototype._getMeshes = function () {
  84599. var meshes = new Array();
  84600. // Root mesh is always first.
  84601. meshes.push(this._rootNode.babylonMesh);
  84602. var nodes = this._gltf.nodes;
  84603. if (nodes) {
  84604. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  84605. var node = nodes_1[_i];
  84606. if (node.babylonMesh) {
  84607. meshes.push(node.babylonMesh);
  84608. }
  84609. }
  84610. }
  84611. return meshes;
  84612. };
  84613. GLTFLoader.prototype._getSkeletons = function () {
  84614. var skeletons = new Array();
  84615. var skins = this._gltf.skins;
  84616. if (skins) {
  84617. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  84618. var skin = skins_1[_i];
  84619. if (skin.babylonSkeleton) {
  84620. skeletons.push(skin.babylonSkeleton);
  84621. }
  84622. }
  84623. }
  84624. return skeletons;
  84625. };
  84626. GLTFLoader.prototype._startAnimations = function () {
  84627. var animations = this._gltf.animations;
  84628. if (!animations) {
  84629. return;
  84630. }
  84631. switch (this.animationStartMode) {
  84632. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  84633. // do nothing
  84634. break;
  84635. }
  84636. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  84637. var animation = animations[0];
  84638. for (var _i = 0, _a = animation.targets; _i < _a.length; _i++) {
  84639. var target = _a[_i];
  84640. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  84641. }
  84642. break;
  84643. }
  84644. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  84645. for (var _b = 0, animations_1 = animations; _b < animations_1.length; _b++) {
  84646. var animation = animations_1[_b];
  84647. for (var _c = 0, _d = animation.targets; _c < _d.length; _c++) {
  84648. var target = _d[_c];
  84649. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  84650. }
  84651. }
  84652. break;
  84653. }
  84654. default: {
  84655. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  84656. return;
  84657. }
  84658. }
  84659. };
  84660. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  84661. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  84662. if (!scene) {
  84663. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  84664. }
  84665. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  84666. };
  84667. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  84668. var _this = this;
  84669. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  84670. switch (this.coordinateSystemMode) {
  84671. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  84672. if (!this._babylonScene.useRightHandedSystem) {
  84673. this._rootNode.rotation = [0, 1, 0, 0];
  84674. this._rootNode.scale = [1, 1, -1];
  84675. this._loadTransform(this._rootNode);
  84676. }
  84677. break;
  84678. }
  84679. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  84680. this._babylonScene.useRightHandedSystem = true;
  84681. break;
  84682. }
  84683. default: {
  84684. BABYLON.Tools.Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  84685. return;
  84686. }
  84687. }
  84688. this.onMeshLoadedObservable.notifyObservers(this._rootNode.babylonMesh);
  84689. var nodeIndices = scene.nodes;
  84690. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  84691. node.parent = parentNode;
  84692. return true;
  84693. }, this._rootNode);
  84694. if (nodeNames) {
  84695. if (!(nodeNames instanceof Array)) {
  84696. nodeNames = [nodeNames];
  84697. }
  84698. var filteredNodeIndices_1 = new Array();
  84699. this._traverseNodes(context, nodeIndices, function (node) {
  84700. if (nodeNames.indexOf(node.name) !== -1) {
  84701. filteredNodeIndices_1.push(node.index);
  84702. node.parent = _this._rootNode;
  84703. return false;
  84704. }
  84705. return true;
  84706. }, this._rootNode);
  84707. nodeIndices = filteredNodeIndices_1;
  84708. }
  84709. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  84710. var index = nodeIndices_1[_i];
  84711. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  84712. if (!node) {
  84713. throw new Error(context + ": Failed to find node " + index);
  84714. }
  84715. this._loadNode("#/nodes/" + index, node);
  84716. }
  84717. // Disable the root mesh until the asset is ready to render.
  84718. this._rootNode.babylonMesh.setEnabled(false);
  84719. };
  84720. GLTFLoader.prototype._loadNode = function (context, node) {
  84721. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  84722. return;
  84723. }
  84724. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  84725. this._loadTransform(node);
  84726. if (node.mesh != null) {
  84727. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  84728. if (!mesh) {
  84729. throw new Error(context + ": Failed to find mesh " + node.mesh);
  84730. }
  84731. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  84732. }
  84733. node.babylonMesh.parent = node.parent.babylonMesh;
  84734. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  84735. node.babylonAnimationTargets.push(node.babylonMesh);
  84736. if (node.skin != null) {
  84737. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  84738. if (!skin_1) {
  84739. throw new Error(context + ": Failed to find skin " + node.skin);
  84740. }
  84741. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  84742. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  84743. node.babylonMesh._refreshBoundingInfo(true);
  84744. });
  84745. node.babylonMesh.parent = this._rootNode.babylonMesh;
  84746. node.babylonMesh.position = BABYLON.Vector3.Zero();
  84747. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84748. node.babylonMesh.scaling = BABYLON.Vector3.One();
  84749. }
  84750. if (node.camera != null) {
  84751. // TODO: handle cameras
  84752. }
  84753. if (node.children) {
  84754. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  84755. var index = _a[_i];
  84756. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  84757. if (!childNode) {
  84758. throw new Error(context + ": Failed to find child node " + index);
  84759. }
  84760. this._loadNode("#/nodes/" + index, childNode);
  84761. }
  84762. }
  84763. this.onMeshLoadedObservable.notifyObservers(node.babylonMesh);
  84764. };
  84765. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  84766. var _this = this;
  84767. var primitives = mesh.primitives;
  84768. if (!primitives || primitives.length === 0) {
  84769. throw new Error(context + ": Primitives are missing");
  84770. }
  84771. this._createMorphTargets(context, node, mesh);
  84772. this._loadAllVertexDataAsync(context, mesh, function () {
  84773. _this._loadMorphTargets(context, node, mesh);
  84774. var vertexData = new BABYLON.VertexData();
  84775. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  84776. var primitive = primitives_1[_i];
  84777. vertexData.merge(primitive.vertexData);
  84778. }
  84779. node.babylonMesh.hasVertexAlpha = mesh.hasVertexAlpha;
  84780. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  84781. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  84782. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  84783. node.babylonMesh.subMeshes = [];
  84784. var verticesStart = 0;
  84785. var indicesStart = 0;
  84786. for (var index = 0; index < primitives.length; index++) {
  84787. var vertexData_1 = primitives[index].vertexData;
  84788. var verticesCount = vertexData_1.positions.length;
  84789. var indicesCount = vertexData_1.indices.length;
  84790. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  84791. verticesStart += verticesCount;
  84792. indicesStart += indicesCount;
  84793. }
  84794. ;
  84795. });
  84796. if (primitives.length === 1) {
  84797. var primitive = primitives[0];
  84798. if (primitive.material == null) {
  84799. node.babylonMesh.material = this._getDefaultMaterial();
  84800. }
  84801. else {
  84802. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  84803. if (!material) {
  84804. throw new Error(context + ": Failed to find material " + primitive.material);
  84805. }
  84806. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  84807. if (isNew) {
  84808. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  84809. }
  84810. node.babylonMesh.material = babylonMaterial;
  84811. });
  84812. }
  84813. }
  84814. else {
  84815. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  84816. node.babylonMesh.material = multiMaterial;
  84817. var subMaterials_1 = multiMaterial.subMaterials;
  84818. var _loop_1 = function (index) {
  84819. var primitive = primitives[index];
  84820. if (primitive.material == null) {
  84821. subMaterials_1[index] = this_1._getDefaultMaterial();
  84822. }
  84823. else {
  84824. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  84825. if (!material) {
  84826. throw new Error(context + ": Failed to find material " + primitive.material);
  84827. }
  84828. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  84829. if (isNew) {
  84830. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  84831. }
  84832. subMaterials_1[index] = babylonMaterial;
  84833. });
  84834. }
  84835. };
  84836. var this_1 = this;
  84837. for (var index = 0; index < primitives.length; index++) {
  84838. _loop_1(index);
  84839. }
  84840. ;
  84841. }
  84842. };
  84843. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  84844. var primitives = mesh.primitives;
  84845. var numRemainingPrimitives = primitives.length;
  84846. var _loop_2 = function (index) {
  84847. var primitive = primitives[index];
  84848. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  84849. primitive.vertexData = vertexData;
  84850. if (--numRemainingPrimitives === 0) {
  84851. onSuccess();
  84852. }
  84853. });
  84854. };
  84855. var this_2 = this;
  84856. for (var index = 0; index < primitives.length; index++) {
  84857. _loop_2(index);
  84858. }
  84859. };
  84860. /**
  84861. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  84862. * @param {ArrayBufferView} data
  84863. * @param {IGLTFAccessor} accessor
  84864. */
  84865. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  84866. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  84867. return data;
  84868. }
  84869. var buffer = data;
  84870. var factor = 1;
  84871. switch (accessor.componentType) {
  84872. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  84873. factor = 1 / 255;
  84874. break;
  84875. }
  84876. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  84877. factor = 1 / 65535;
  84878. break;
  84879. }
  84880. default: {
  84881. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  84882. }
  84883. }
  84884. var result = new Float32Array(accessor.count * 2);
  84885. for (var i = 0; i < result.length; ++i) {
  84886. result[i] = buffer[i] * factor;
  84887. }
  84888. return result;
  84889. };
  84890. /**
  84891. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  84892. * @param {ArrayBufferView} data
  84893. * @param {IGLTFAccessor} accessor
  84894. */
  84895. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  84896. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  84897. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  84898. return data;
  84899. }
  84900. var buffer = data;
  84901. var factor = 1;
  84902. switch (accessor.componentType) {
  84903. case GLTF2.EComponentType.FLOAT: {
  84904. factor = 1;
  84905. break;
  84906. }
  84907. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  84908. factor = 1 / 255;
  84909. break;
  84910. }
  84911. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  84912. factor = 1 / 65535;
  84913. break;
  84914. }
  84915. default: {
  84916. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  84917. }
  84918. }
  84919. var result = new Float32Array(accessor.count * 4);
  84920. if (colorComponentCount === 4) {
  84921. for (var i = 0; i < result.length; ++i) {
  84922. result[i] = buffer[i] * factor;
  84923. }
  84924. }
  84925. else {
  84926. var offset = 0;
  84927. for (var i = 0; i < result.length; ++i) {
  84928. if ((i + 1) % 4 === 0) {
  84929. result[i] = 1;
  84930. }
  84931. else {
  84932. result[i] = buffer[offset++] * factor;
  84933. }
  84934. }
  84935. }
  84936. return result;
  84937. };
  84938. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  84939. var _this = this;
  84940. var attributes = primitive.attributes;
  84941. if (!attributes) {
  84942. throw new Error(context + ": Attributes are missing");
  84943. }
  84944. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  84945. // TODO: handle other primitive modes
  84946. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  84947. }
  84948. var vertexData = new BABYLON.VertexData();
  84949. var numRemainingAttributes = Object.keys(attributes).length;
  84950. var _loop_3 = function (attribute) {
  84951. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  84952. if (!accessor) {
  84953. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  84954. }
  84955. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  84956. switch (attribute) {
  84957. case "POSITION": {
  84958. vertexData.positions = data;
  84959. break;
  84960. }
  84961. case "NORMAL": {
  84962. vertexData.normals = data;
  84963. break;
  84964. }
  84965. case "TANGENT": {
  84966. vertexData.tangents = data;
  84967. break;
  84968. }
  84969. case "TEXCOORD_0": {
  84970. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  84971. break;
  84972. }
  84973. case "TEXCOORD_1": {
  84974. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  84975. break;
  84976. }
  84977. case "JOINTS_0": {
  84978. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  84979. break;
  84980. }
  84981. case "WEIGHTS_0": {
  84982. //TODO: need to add support for normalized weights.
  84983. vertexData.matricesWeights = data;
  84984. break;
  84985. }
  84986. case "COLOR_0": {
  84987. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  84988. var hasVertexAlpha = GLTFLoader._GetNumComponents(context, accessor.type) === 4;
  84989. if (!mesh.hasVertexAlpha && hasVertexAlpha) {
  84990. mesh.hasVertexAlpha = hasVertexAlpha;
  84991. }
  84992. break;
  84993. }
  84994. default: {
  84995. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  84996. break;
  84997. }
  84998. }
  84999. if (--numRemainingAttributes === 0) {
  85000. if (primitive.indices == null) {
  85001. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  85002. for (var i = 0; i < vertexData.indices.length; i++) {
  85003. vertexData.indices[i] = i;
  85004. }
  85005. onSuccess(vertexData);
  85006. }
  85007. else {
  85008. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  85009. if (!indicesAccessor) {
  85010. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  85011. }
  85012. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  85013. vertexData.indices = data;
  85014. onSuccess(vertexData);
  85015. });
  85016. }
  85017. }
  85018. });
  85019. };
  85020. var this_3 = this;
  85021. for (var attribute in attributes) {
  85022. _loop_3(attribute);
  85023. }
  85024. };
  85025. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  85026. var primitives = mesh.primitives;
  85027. var targets = primitives[0].targets;
  85028. if (!targets) {
  85029. return;
  85030. }
  85031. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  85032. var primitive = primitives_2[_i];
  85033. if (!primitive.targets || primitive.targets.length != targets.length) {
  85034. throw new Error(context + ": All primitives are required to list the same number of targets");
  85035. }
  85036. }
  85037. var morphTargetManager = new BABYLON.MorphTargetManager();
  85038. node.babylonMesh.morphTargetManager = morphTargetManager;
  85039. for (var index = 0; index < targets.length; index++) {
  85040. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  85041. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  85042. }
  85043. };
  85044. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  85045. var morphTargetManager = node.babylonMesh.morphTargetManager;
  85046. if (!morphTargetManager) {
  85047. return;
  85048. }
  85049. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  85050. var numTargets = morphTargetManager.numTargets;
  85051. for (var index = 0; index < numTargets; index++) {
  85052. var vertexData = new BABYLON.VertexData();
  85053. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  85054. var primitive = _a[_i];
  85055. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  85056. }
  85057. if (!vertexData.positions) {
  85058. throw new Error(context + ": Positions are missing");
  85059. }
  85060. var target = morphTargetManager.getTarget(index);
  85061. target.setPositions(vertexData.positions);
  85062. target.setNormals(vertexData.normals);
  85063. target.setTangents(vertexData.tangents);
  85064. }
  85065. });
  85066. };
  85067. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  85068. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  85069. var _loop_4 = function (primitive) {
  85070. var targets = primitive.targets;
  85071. primitive.targetsVertexData = new Array(targets.length);
  85072. var _loop_5 = function (index) {
  85073. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  85074. primitive.targetsVertexData[index] = vertexData;
  85075. if (--numRemainingTargets === 0) {
  85076. onSuccess();
  85077. }
  85078. });
  85079. };
  85080. for (var index = 0; index < targets.length; index++) {
  85081. _loop_5(index);
  85082. }
  85083. };
  85084. var this_4 = this;
  85085. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  85086. var primitive = _a[_i];
  85087. _loop_4(primitive);
  85088. }
  85089. };
  85090. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  85091. var targetVertexData = new BABYLON.VertexData();
  85092. var numRemainingAttributes = Object.keys(attributes).length;
  85093. var _loop_6 = function (attribute) {
  85094. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  85095. if (!accessor) {
  85096. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  85097. }
  85098. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  85099. // glTF stores morph target information as deltas while babylon.js expects the final data.
  85100. // As a result we have to add the original data to the delta to calculate the final data.
  85101. var values = data;
  85102. switch (attribute) {
  85103. case "POSITION": {
  85104. for (var i = 0; i < values.length; i++) {
  85105. values[i] += vertexData.positions[i];
  85106. }
  85107. targetVertexData.positions = values;
  85108. break;
  85109. }
  85110. case "NORMAL": {
  85111. for (var i = 0; i < values.length; i++) {
  85112. values[i] += vertexData.normals[i];
  85113. }
  85114. targetVertexData.normals = values;
  85115. break;
  85116. }
  85117. case "TANGENT": {
  85118. // Tangent data for morph targets is stored as xyz delta.
  85119. // The vertexData.tangent is stored as xyzw.
  85120. // So we need to skip every fourth vertexData.tangent.
  85121. for (var i = 0, j = 0; i < values.length; i++, j++) {
  85122. values[i] += vertexData.tangents[j];
  85123. if ((i + 1) % 3 == 0) {
  85124. j++;
  85125. }
  85126. }
  85127. targetVertexData.tangents = values;
  85128. break;
  85129. }
  85130. default: {
  85131. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  85132. break;
  85133. }
  85134. }
  85135. if (--numRemainingAttributes === 0) {
  85136. onSuccess(targetVertexData);
  85137. }
  85138. });
  85139. };
  85140. var this_5 = this;
  85141. for (var attribute in attributes) {
  85142. _loop_6(attribute);
  85143. }
  85144. };
  85145. GLTFLoader.prototype._loadTransform = function (node) {
  85146. var position = BABYLON.Vector3.Zero();
  85147. var rotation = BABYLON.Quaternion.Identity();
  85148. var scaling = BABYLON.Vector3.One();
  85149. if (node.matrix) {
  85150. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  85151. matrix.decompose(scaling, rotation, position);
  85152. }
  85153. else {
  85154. if (node.translation)
  85155. position = BABYLON.Vector3.FromArray(node.translation);
  85156. if (node.rotation)
  85157. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  85158. if (node.scale)
  85159. scaling = BABYLON.Vector3.FromArray(node.scale);
  85160. }
  85161. node.babylonMesh.position = position;
  85162. node.babylonMesh.rotationQuaternion = rotation;
  85163. node.babylonMesh.scaling = scaling;
  85164. };
  85165. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  85166. var _this = this;
  85167. if (skin.babylonSkeleton) {
  85168. onSuccess();
  85169. return;
  85170. }
  85171. var skeletonId = "skeleton" + skin.index;
  85172. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  85173. if (skin.inverseBindMatrices == null) {
  85174. this._loadBones(context, skin, null);
  85175. onSuccess();
  85176. }
  85177. else {
  85178. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  85179. if (!accessor) {
  85180. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  85181. }
  85182. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  85183. _this._loadBones(context, skin, data);
  85184. onSuccess();
  85185. });
  85186. }
  85187. };
  85188. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  85189. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  85190. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  85191. node.babylonAnimationTargets.push(babylonBone);
  85192. return babylonBone;
  85193. };
  85194. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  85195. var babylonBones = {};
  85196. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  85197. var index = _a[_i];
  85198. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  85199. if (!node) {
  85200. throw new Error(context + ": Failed to find joint " + index);
  85201. }
  85202. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  85203. }
  85204. };
  85205. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  85206. var babylonBone = babylonBones[node.index];
  85207. if (babylonBone) {
  85208. return babylonBone;
  85209. }
  85210. var boneIndex = skin.joints.indexOf(node.index);
  85211. var baseMatrix = BABYLON.Matrix.Identity();
  85212. if (inverseBindMatrixData && boneIndex !== -1) {
  85213. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  85214. baseMatrix.invertToRef(baseMatrix);
  85215. }
  85216. var babylonParentBone = null;
  85217. if (node.parent !== this._rootNode) {
  85218. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  85219. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  85220. }
  85221. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  85222. babylonBones[node.index] = babylonBone;
  85223. return babylonBone;
  85224. };
  85225. GLTFLoader.prototype._getNodeMatrix = function (node) {
  85226. return node.matrix ?
  85227. BABYLON.Matrix.FromArray(node.matrix) :
  85228. 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());
  85229. };
  85230. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  85231. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  85232. var index = indices_1[_i];
  85233. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  85234. if (!node) {
  85235. throw new Error(context + ": Failed to find node " + index);
  85236. }
  85237. this._traverseNode(context, node, action, parentNode);
  85238. }
  85239. };
  85240. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  85241. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  85242. return;
  85243. }
  85244. if (!action(node, parentNode)) {
  85245. return;
  85246. }
  85247. if (node.children) {
  85248. this._traverseNodes(context, node.children, action, node);
  85249. }
  85250. };
  85251. GLTFLoader.prototype._loadAnimations = function () {
  85252. var animations = this._gltf.animations;
  85253. if (!animations) {
  85254. return;
  85255. }
  85256. for (var index = 0; index < animations.length; index++) {
  85257. var animation = animations[index];
  85258. this._loadAnimation("#/animations/" + index, animation);
  85259. }
  85260. };
  85261. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  85262. animation.targets = [];
  85263. for (var index = 0; index < animation.channels.length; index++) {
  85264. var channel = GLTFLoader._GetProperty(animation.channels, index);
  85265. if (!channel) {
  85266. throw new Error(context + ": Failed to find channel " + index);
  85267. }
  85268. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  85269. if (!sampler) {
  85270. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  85271. }
  85272. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  85273. }
  85274. };
  85275. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  85276. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  85277. if (!targetNode) {
  85278. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  85279. }
  85280. var targetPath;
  85281. var animationType;
  85282. switch (channel.target.path) {
  85283. case "translation": {
  85284. targetPath = "position";
  85285. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  85286. break;
  85287. }
  85288. case "rotation": {
  85289. targetPath = "rotationQuaternion";
  85290. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  85291. break;
  85292. }
  85293. case "scale": {
  85294. targetPath = "scaling";
  85295. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  85296. break;
  85297. }
  85298. case "weights": {
  85299. targetPath = "influence";
  85300. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  85301. break;
  85302. }
  85303. default: {
  85304. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  85305. }
  85306. }
  85307. var inputData;
  85308. var outputData;
  85309. var checkSuccess = function () {
  85310. if (!inputData || !outputData) {
  85311. return;
  85312. }
  85313. var outputBufferOffset = 0;
  85314. var getNextOutputValue;
  85315. switch (targetPath) {
  85316. case "position": {
  85317. getNextOutputValue = function () {
  85318. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  85319. outputBufferOffset += 3;
  85320. return value;
  85321. };
  85322. break;
  85323. }
  85324. case "rotationQuaternion": {
  85325. getNextOutputValue = function () {
  85326. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  85327. outputBufferOffset += 4;
  85328. return value;
  85329. };
  85330. break;
  85331. }
  85332. case "scaling": {
  85333. getNextOutputValue = function () {
  85334. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  85335. outputBufferOffset += 3;
  85336. return value;
  85337. };
  85338. break;
  85339. }
  85340. case "influence": {
  85341. getNextOutputValue = function () {
  85342. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  85343. var value = new Array(numTargets);
  85344. for (var i = 0; i < numTargets; i++) {
  85345. value[i] = outputData[outputBufferOffset++];
  85346. }
  85347. return value;
  85348. };
  85349. break;
  85350. }
  85351. }
  85352. sampler.interpolation = sampler.interpolation || "LINEAR";
  85353. var getNextKey;
  85354. switch (sampler.interpolation) {
  85355. case "STEP": {
  85356. getNextKey = function (frameIndex) { return ({
  85357. frame: inputData[frameIndex],
  85358. value: getNextOutputValue(),
  85359. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  85360. }); };
  85361. break;
  85362. }
  85363. case "LINEAR": {
  85364. getNextKey = function (frameIndex) { return ({
  85365. frame: inputData[frameIndex],
  85366. value: getNextOutputValue()
  85367. }); };
  85368. break;
  85369. }
  85370. case "CUBICSPLINE": {
  85371. getNextKey = function (frameIndex) { return ({
  85372. frame: inputData[frameIndex],
  85373. inTangent: getNextOutputValue(),
  85374. value: getNextOutputValue(),
  85375. outTangent: getNextOutputValue()
  85376. }); };
  85377. break;
  85378. }
  85379. default: {
  85380. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  85381. }
  85382. }
  85383. ;
  85384. var keys;
  85385. if (inputData.length === 1) {
  85386. var key = getNextKey(0);
  85387. keys = [
  85388. { frame: key.frame, value: key.value },
  85389. { frame: key.frame + 1, value: key.value }
  85390. ];
  85391. }
  85392. else {
  85393. keys = new Array(inputData.length);
  85394. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  85395. keys[frameIndex] = getNextKey(frameIndex);
  85396. }
  85397. }
  85398. if (targetPath === "influence") {
  85399. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  85400. var _loop_7 = function (targetIndex) {
  85401. var morphTarget = morphTargetManager.getTarget(targetIndex);
  85402. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  85403. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  85404. babylonAnimation.setKeys(keys.map(function (key) { return ({
  85405. frame: key.frame,
  85406. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  85407. value: key.value[targetIndex],
  85408. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  85409. }); }));
  85410. morphTarget.animations.push(babylonAnimation);
  85411. animation.targets.push(morphTarget);
  85412. };
  85413. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  85414. _loop_7(targetIndex);
  85415. }
  85416. }
  85417. else {
  85418. var animationName = animation.name || "anim" + animation.index;
  85419. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  85420. babylonAnimation.setKeys(keys);
  85421. if (targetNode.babylonAnimationTargets) {
  85422. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  85423. var target = _a[_i];
  85424. target.animations.push(babylonAnimation.clone());
  85425. animation.targets.push(target);
  85426. }
  85427. }
  85428. }
  85429. };
  85430. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  85431. if (!inputAccessor) {
  85432. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  85433. }
  85434. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  85435. inputData = data;
  85436. checkSuccess();
  85437. });
  85438. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  85439. if (!outputAccessor) {
  85440. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  85441. }
  85442. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  85443. outputData = data;
  85444. checkSuccess();
  85445. });
  85446. };
  85447. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  85448. var _this = this;
  85449. this._addPendingData(buffer);
  85450. if (buffer.loadedData) {
  85451. onSuccess(buffer.loadedData);
  85452. this._removePendingData(buffer);
  85453. }
  85454. else if (buffer.loadedObservable) {
  85455. buffer.loadedObservable.add(function (buffer) {
  85456. onSuccess(buffer.loadedData);
  85457. _this._removePendingData(buffer);
  85458. });
  85459. }
  85460. else {
  85461. if (!buffer.uri) {
  85462. throw new Error(context + ": Uri is missing");
  85463. }
  85464. buffer.loadedObservable = new BABYLON.Observable();
  85465. buffer.loadedObservable.add(function (buffer) {
  85466. onSuccess(buffer.loadedData);
  85467. _this._removePendingData(buffer);
  85468. });
  85469. this._loadUriAsync(context, buffer.uri, function (data) {
  85470. buffer.loadedData = data;
  85471. buffer.loadedObservable.notifyObservers(buffer);
  85472. buffer.loadedObservable = undefined;
  85473. });
  85474. }
  85475. };
  85476. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  85477. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  85478. if (!buffer) {
  85479. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  85480. }
  85481. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  85482. var data;
  85483. try {
  85484. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  85485. }
  85486. catch (e) {
  85487. throw new Error(context + ": " + e.message);
  85488. }
  85489. onSuccess(data);
  85490. });
  85491. };
  85492. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  85493. var _this = this;
  85494. if (accessor.sparse) {
  85495. throw new Error(context + ": Sparse accessors are not currently supported");
  85496. }
  85497. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  85498. if (!bufferView) {
  85499. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  85500. }
  85501. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  85502. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  85503. var data;
  85504. var byteOffset = accessor.byteOffset || 0;
  85505. var byteStride = bufferView.byteStride;
  85506. if (byteStride === 0) {
  85507. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  85508. }
  85509. try {
  85510. switch (accessor.componentType) {
  85511. case GLTF2.EComponentType.BYTE: {
  85512. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85513. break;
  85514. }
  85515. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  85516. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85517. break;
  85518. }
  85519. case GLTF2.EComponentType.SHORT: {
  85520. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85521. break;
  85522. }
  85523. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  85524. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85525. break;
  85526. }
  85527. case GLTF2.EComponentType.UNSIGNED_INT: {
  85528. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85529. break;
  85530. }
  85531. case GLTF2.EComponentType.FLOAT: {
  85532. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85533. break;
  85534. }
  85535. default: {
  85536. throw new Error(context + ": Invalid component type " + accessor.componentType);
  85537. }
  85538. }
  85539. }
  85540. catch (e) {
  85541. throw new Error(context + ": " + e);
  85542. }
  85543. onSuccess(data);
  85544. });
  85545. };
  85546. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  85547. byteOffset += data.byteOffset;
  85548. var targetLength = count * numComponents;
  85549. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  85550. return new typedArray(data.buffer, byteOffset, targetLength);
  85551. }
  85552. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  85553. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  85554. var targetBuffer = new typedArray(targetLength);
  85555. var sourceIndex = 0;
  85556. var targetIndex = 0;
  85557. while (targetIndex < targetLength) {
  85558. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  85559. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  85560. targetIndex++;
  85561. }
  85562. sourceIndex += elementStride;
  85563. }
  85564. return targetBuffer;
  85565. };
  85566. GLTFLoader.prototype._addPendingData = function (data) {
  85567. if (!this._renderReady) {
  85568. this._renderPendingCount++;
  85569. }
  85570. this._addLoaderPendingData(data);
  85571. };
  85572. GLTFLoader.prototype._removePendingData = function (data) {
  85573. var _this = this;
  85574. if (!this._renderReady) {
  85575. if (--this._renderPendingCount === 0) {
  85576. this._addLoaderPendingData(this);
  85577. this._compileMaterialsAsync(function () {
  85578. _this._compileShadowGeneratorsAsync(function () {
  85579. _this._removeLoaderPendingData(_this);
  85580. _this._renderReady = true;
  85581. _this._onRenderReady();
  85582. });
  85583. });
  85584. }
  85585. }
  85586. this._removeLoaderPendingData(data);
  85587. };
  85588. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  85589. this._loaderPendingCount++;
  85590. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  85591. var tracker = _a[_i];
  85592. tracker._addPendingData(data);
  85593. }
  85594. };
  85595. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  85596. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  85597. var tracker = _a[_i];
  85598. tracker._removePendingData(data);
  85599. }
  85600. if (--this._loaderPendingCount === 0) {
  85601. this._onComplete();
  85602. }
  85603. };
  85604. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  85605. var _this = this;
  85606. var tracker = new GLTFLoaderTracker(function () {
  85607. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  85608. onComplete();
  85609. });
  85610. this._loaderTrackers.push(tracker);
  85611. this._addLoaderPendingData(tracker);
  85612. action();
  85613. this._removeLoaderPendingData(tracker);
  85614. };
  85615. GLTFLoader.prototype._getDefaultMaterial = function () {
  85616. if (!this._defaultMaterial) {
  85617. var id = "__gltf_default";
  85618. var material = this._babylonScene.getMaterialByName(id);
  85619. if (!material) {
  85620. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  85621. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  85622. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  85623. material.metallic = 1;
  85624. material.roughness = 1;
  85625. }
  85626. this._defaultMaterial = material;
  85627. }
  85628. return this._defaultMaterial;
  85629. };
  85630. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  85631. var babylonMaterial = material.babylonMaterial;
  85632. // Ensure metallic workflow
  85633. babylonMaterial.metallic = 1;
  85634. babylonMaterial.roughness = 1;
  85635. var properties = material.pbrMetallicRoughness;
  85636. if (!properties) {
  85637. return;
  85638. }
  85639. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  85640. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  85641. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  85642. if (properties.baseColorTexture) {
  85643. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  85644. if (!texture) {
  85645. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  85646. }
  85647. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  85648. }
  85649. if (properties.metallicRoughnessTexture) {
  85650. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  85651. if (!texture) {
  85652. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  85653. }
  85654. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  85655. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  85656. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  85657. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  85658. }
  85659. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  85660. };
  85661. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  85662. if (material.babylonMaterial) {
  85663. assign(material.babylonMaterial, false);
  85664. return;
  85665. }
  85666. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  85667. return;
  85668. }
  85669. this._createPbrMaterial(material);
  85670. this._loadMaterialBaseProperties(context, material);
  85671. this._loadMaterialMetallicRoughnessProperties(context, material);
  85672. assign(material.babylonMaterial, true);
  85673. };
  85674. GLTFLoader.prototype._createPbrMaterial = function (material) {
  85675. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  85676. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  85677. material.babylonMaterial = babylonMaterial;
  85678. };
  85679. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  85680. var babylonMaterial = material.babylonMaterial;
  85681. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  85682. if (material.doubleSided) {
  85683. babylonMaterial.backFaceCulling = false;
  85684. babylonMaterial.twoSidedLighting = true;
  85685. }
  85686. if (material.normalTexture) {
  85687. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  85688. if (!texture) {
  85689. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  85690. }
  85691. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  85692. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  85693. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  85694. if (material.normalTexture.scale != null) {
  85695. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  85696. }
  85697. }
  85698. if (material.occlusionTexture) {
  85699. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  85700. if (!texture) {
  85701. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  85702. }
  85703. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  85704. babylonMaterial.useAmbientInGrayScale = true;
  85705. if (material.occlusionTexture.strength != null) {
  85706. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  85707. }
  85708. }
  85709. if (material.emissiveTexture) {
  85710. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  85711. if (!texture) {
  85712. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  85713. }
  85714. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  85715. }
  85716. };
  85717. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  85718. var babylonMaterial = material.babylonMaterial;
  85719. var alphaMode = material.alphaMode || "OPAQUE";
  85720. switch (alphaMode) {
  85721. case "OPAQUE": {
  85722. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  85723. break;
  85724. }
  85725. case "MASK": {
  85726. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  85727. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  85728. if (colorFactor) {
  85729. if (colorFactor[3] == 0) {
  85730. babylonMaterial.alphaCutOff = 1;
  85731. }
  85732. else {
  85733. babylonMaterial.alphaCutOff /= colorFactor[3];
  85734. }
  85735. }
  85736. if (babylonMaterial.albedoTexture) {
  85737. babylonMaterial.albedoTexture.hasAlpha = true;
  85738. }
  85739. break;
  85740. }
  85741. case "BLEND": {
  85742. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  85743. if (colorFactor) {
  85744. babylonMaterial.alpha = colorFactor[3];
  85745. }
  85746. if (babylonMaterial.albedoTexture) {
  85747. babylonMaterial.albedoTexture.hasAlpha = true;
  85748. babylonMaterial.useAlphaFromAlbedoTexture = true;
  85749. }
  85750. break;
  85751. }
  85752. default: {
  85753. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  85754. }
  85755. }
  85756. };
  85757. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  85758. var _this = this;
  85759. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  85760. if (!sampler) {
  85761. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  85762. }
  85763. this._loadSampler("#/samplers/" + sampler.index, sampler);
  85764. this._addPendingData(texture);
  85765. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  85766. _this._tryCatchOnError(function () {
  85767. _this._removePendingData(texture);
  85768. });
  85769. }, function (message) {
  85770. _this._tryCatchOnError(function () {
  85771. throw new Error(context + ": " + message);
  85772. });
  85773. });
  85774. if (texture.url) {
  85775. babylonTexture.updateURL(texture.url);
  85776. }
  85777. else if (texture.dataReadyObservable) {
  85778. texture.dataReadyObservable.add(function (texture) {
  85779. babylonTexture.updateURL(texture.url);
  85780. });
  85781. }
  85782. else {
  85783. texture.dataReadyObservable = new BABYLON.Observable();
  85784. texture.dataReadyObservable.add(function (texture) {
  85785. babylonTexture.updateURL(texture.url);
  85786. });
  85787. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  85788. if (!image_1) {
  85789. throw new Error(context + ": Failed to find source " + texture.source);
  85790. }
  85791. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  85792. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  85793. texture.dataReadyObservable.notifyObservers(texture);
  85794. texture.dataReadyObservable = undefined;
  85795. });
  85796. }
  85797. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  85798. babylonTexture.wrapU = sampler.wrapU;
  85799. babylonTexture.wrapV = sampler.wrapV;
  85800. babylonTexture.name = texture.name || "texture" + texture.index;
  85801. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  85802. return babylonTexture;
  85803. };
  85804. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  85805. if (sampler.noMipMaps != undefined) {
  85806. return;
  85807. }
  85808. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  85809. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  85810. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  85811. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  85812. };
  85813. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  85814. if (image.uri) {
  85815. this._loadUriAsync(context, image.uri, onSuccess);
  85816. }
  85817. else {
  85818. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  85819. if (!bufferView) {
  85820. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  85821. }
  85822. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  85823. }
  85824. };
  85825. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  85826. var _this = this;
  85827. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  85828. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  85829. return;
  85830. }
  85831. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  85832. throw new Error(context + ": Uri '" + uri + "' is invalid");
  85833. }
  85834. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  85835. _this._tryCatchOnError(function () {
  85836. onSuccess(new Uint8Array(data));
  85837. });
  85838. }, function (event) {
  85839. _this._tryCatchOnError(function () {
  85840. if (request && !_this._renderReady) {
  85841. request._lengthComputable = event.lengthComputable;
  85842. request._loaded = event.loaded;
  85843. request._total = event.total;
  85844. _this._onProgress();
  85845. }
  85846. });
  85847. }, this._babylonScene.database, true, function (request, exception) {
  85848. _this._tryCatchOnError(function () {
  85849. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  85850. });
  85851. });
  85852. this._requests.push(request);
  85853. request.onCompleteObservable.add(function () {
  85854. _this._requests.splice(_this._requests.indexOf(request), 1);
  85855. });
  85856. };
  85857. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  85858. if (this._disposed) {
  85859. return;
  85860. }
  85861. try {
  85862. handler();
  85863. }
  85864. catch (e) {
  85865. BABYLON.Tools.Error("glTF Loader: " + e.message);
  85866. if (this._errorCallback) {
  85867. this._errorCallback(e.message, e);
  85868. }
  85869. this.dispose();
  85870. }
  85871. };
  85872. GLTFLoader._AssignIndices = function (array) {
  85873. if (array) {
  85874. for (var index = 0; index < array.length; index++) {
  85875. array[index].index = index;
  85876. }
  85877. }
  85878. };
  85879. GLTFLoader._GetProperty = function (array, index) {
  85880. if (!array || index == undefined || !array[index]) {
  85881. return null;
  85882. }
  85883. return array[index];
  85884. };
  85885. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  85886. // Set defaults if undefined
  85887. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  85888. switch (mode) {
  85889. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  85890. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  85891. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  85892. default:
  85893. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  85894. return BABYLON.Texture.WRAP_ADDRESSMODE;
  85895. }
  85896. };
  85897. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  85898. // Set defaults if undefined
  85899. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  85900. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  85901. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  85902. switch (minFilter) {
  85903. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  85904. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  85905. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  85906. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  85907. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  85908. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  85909. default:
  85910. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  85911. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  85912. }
  85913. }
  85914. else {
  85915. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  85916. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  85917. }
  85918. switch (minFilter) {
  85919. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  85920. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  85921. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  85922. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  85923. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  85924. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  85925. default:
  85926. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  85927. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  85928. }
  85929. }
  85930. };
  85931. GLTFLoader._GetNumComponents = function (context, type) {
  85932. switch (type) {
  85933. case "SCALAR": return 1;
  85934. case "VEC2": return 2;
  85935. case "VEC3": return 3;
  85936. case "VEC4": return 4;
  85937. case "MAT2": return 4;
  85938. case "MAT3": return 9;
  85939. case "MAT4": return 16;
  85940. }
  85941. throw new Error(context + ": Invalid type " + type);
  85942. };
  85943. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  85944. var _this = this;
  85945. if (this.useClipPlane) {
  85946. babylonMaterial.forceCompilation(babylonMesh, function () {
  85947. babylonMaterial.forceCompilation(babylonMesh, function () {
  85948. _this._tryCatchOnError(onSuccess);
  85949. }, { clipPlane: true });
  85950. });
  85951. }
  85952. else {
  85953. babylonMaterial.forceCompilation(babylonMesh, function () {
  85954. _this._tryCatchOnError(onSuccess);
  85955. });
  85956. }
  85957. };
  85958. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  85959. if (!this.compileMaterials || !this._gltf.materials) {
  85960. onSuccess();
  85961. return;
  85962. }
  85963. var meshes = this._getMeshes();
  85964. var remaining = 0;
  85965. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  85966. var mesh = meshes_1[_i];
  85967. if (mesh.material instanceof BABYLON.MultiMaterial) {
  85968. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  85969. var subMaterial = _b[_a];
  85970. if (subMaterial) {
  85971. remaining++;
  85972. }
  85973. }
  85974. }
  85975. else if (mesh.material) {
  85976. remaining++;
  85977. }
  85978. }
  85979. if (remaining === 0) {
  85980. onSuccess();
  85981. return;
  85982. }
  85983. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  85984. var mesh = meshes_2[_c];
  85985. if (mesh.material instanceof BABYLON.MultiMaterial) {
  85986. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  85987. var subMaterial = _e[_d];
  85988. if (subMaterial) {
  85989. this._compileMaterialAsync(subMaterial, mesh, function () {
  85990. if (--remaining === 0) {
  85991. onSuccess();
  85992. }
  85993. });
  85994. }
  85995. }
  85996. }
  85997. else if (mesh.material) {
  85998. this._compileMaterialAsync(mesh.material, mesh, function () {
  85999. if (--remaining === 0) {
  86000. onSuccess();
  86001. }
  86002. });
  86003. }
  86004. }
  86005. };
  86006. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  86007. var _this = this;
  86008. if (!this.compileShadowGenerators) {
  86009. onSuccess();
  86010. return;
  86011. }
  86012. var lights = this._babylonScene.lights;
  86013. var remaining = 0;
  86014. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  86015. var light = lights_1[_i];
  86016. var generator = light.getShadowGenerator();
  86017. if (generator) {
  86018. remaining++;
  86019. }
  86020. }
  86021. if (remaining === 0) {
  86022. onSuccess();
  86023. return;
  86024. }
  86025. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  86026. var light = lights_2[_a];
  86027. var generator = light.getShadowGenerator();
  86028. if (generator) {
  86029. generator.forceCompilation(function () {
  86030. if (--remaining === 0) {
  86031. _this._tryCatchOnError(onSuccess);
  86032. }
  86033. });
  86034. }
  86035. }
  86036. };
  86037. GLTFLoader.prototype._abortRequests = function () {
  86038. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  86039. var request = _a[_i];
  86040. request.abort();
  86041. }
  86042. this._requests.length = 0;
  86043. };
  86044. GLTFLoader.prototype._releaseResources = function () {
  86045. if (this._gltf.textures) {
  86046. for (var _i = 0, _a = this._gltf.textures; _i < _a.length; _i++) {
  86047. var texture = _a[_i];
  86048. if (texture.url) {
  86049. URL.revokeObjectURL(texture.url);
  86050. texture.url = undefined;
  86051. }
  86052. }
  86053. }
  86054. };
  86055. GLTFLoader.Extensions = {};
  86056. return GLTFLoader;
  86057. }());
  86058. GLTF2.GLTFLoader = GLTFLoader;
  86059. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  86060. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86061. })(BABYLON || (BABYLON = {}));
  86062. //# sourceMappingURL=babylon.glTFLoader.js.map
  86063. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86064. var BABYLON;
  86065. (function (BABYLON) {
  86066. var GLTF2;
  86067. (function (GLTF2) {
  86068. /**
  86069. * Utils functions for GLTF
  86070. */
  86071. var GLTFUtils = /** @class */ (function () {
  86072. function GLTFUtils() {
  86073. }
  86074. /**
  86075. * If the uri is a base64 string
  86076. * @param uri: the uri to test
  86077. */
  86078. GLTFUtils.IsBase64 = function (uri) {
  86079. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  86080. };
  86081. /**
  86082. * Decode the base64 uri
  86083. * @param uri: the uri to decode
  86084. */
  86085. GLTFUtils.DecodeBase64 = function (uri) {
  86086. var decodedString = atob(uri.split(",")[1]);
  86087. var bufferLength = decodedString.length;
  86088. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  86089. for (var i = 0; i < bufferLength; i++) {
  86090. bufferView[i] = decodedString.charCodeAt(i);
  86091. }
  86092. return bufferView.buffer;
  86093. };
  86094. GLTFUtils.ValidateUri = function (uri) {
  86095. return (uri.indexOf("..") === -1);
  86096. };
  86097. return GLTFUtils;
  86098. }());
  86099. GLTF2.GLTFUtils = GLTFUtils;
  86100. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86101. })(BABYLON || (BABYLON = {}));
  86102. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  86103. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86104. var BABYLON;
  86105. (function (BABYLON) {
  86106. var GLTF2;
  86107. (function (GLTF2) {
  86108. var GLTFLoaderExtension = /** @class */ (function () {
  86109. function GLTFLoaderExtension() {
  86110. this.enabled = true;
  86111. }
  86112. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  86113. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  86114. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  86115. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  86116. var _this = this;
  86117. if (!property.extensions) {
  86118. return false;
  86119. }
  86120. var extension = property.extensions[this.name];
  86121. if (!extension) {
  86122. return false;
  86123. }
  86124. // Clear out the extension before executing the action to avoid recursing into the same property.
  86125. property.extensions[this.name] = undefined;
  86126. action(context + "extensions/" + this.name, extension, function () {
  86127. // Restore the extension after completing the action.
  86128. property.extensions[_this.name] = extension;
  86129. });
  86130. return true;
  86131. };
  86132. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  86133. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  86134. };
  86135. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  86136. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  86137. };
  86138. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  86139. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  86140. };
  86141. GLTFLoaderExtension._ApplyExtensions = function (action) {
  86142. var extensions = GLTFLoaderExtension._Extensions;
  86143. if (!extensions) {
  86144. return false;
  86145. }
  86146. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  86147. var extension = extensions_1[_i];
  86148. if (extension.enabled && action(extension)) {
  86149. return true;
  86150. }
  86151. }
  86152. return false;
  86153. };
  86154. //
  86155. // Utilities
  86156. //
  86157. GLTFLoaderExtension._Extensions = [];
  86158. return GLTFLoaderExtension;
  86159. }());
  86160. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  86161. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86162. })(BABYLON || (BABYLON = {}));
  86163. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  86164. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  86165. var BABYLON;
  86166. (function (BABYLON) {
  86167. var GLTF2;
  86168. (function (GLTF2) {
  86169. var Extensions;
  86170. (function (Extensions) {
  86171. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  86172. var MSFTLOD = /** @class */ (function (_super) {
  86173. __extends(MSFTLOD, _super);
  86174. function MSFTLOD() {
  86175. var _this = _super !== null && _super.apply(this, arguments) || this;
  86176. /**
  86177. * Specify the minimal delay between LODs in ms (default = 250)
  86178. */
  86179. _this.Delay = 250;
  86180. return _this;
  86181. }
  86182. Object.defineProperty(MSFTLOD.prototype, "name", {
  86183. get: function () {
  86184. return "MSFT_lod";
  86185. },
  86186. enumerable: true,
  86187. configurable: true
  86188. });
  86189. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  86190. return this._loadExtension(context, node, function (context, extension, onComplete) {
  86191. for (var i = extension.ids.length - 1; i >= 0; i--) {
  86192. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  86193. if (!lodNode) {
  86194. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  86195. }
  86196. loader._traverseNode(context, lodNode, action, parentNode);
  86197. }
  86198. loader._traverseNode(context, node, action, parentNode);
  86199. onComplete();
  86200. });
  86201. };
  86202. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  86203. var _this = this;
  86204. return this._loadExtension(context, node, function (context, extension, onComplete) {
  86205. var nodes = [node];
  86206. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  86207. var index = _a[_i];
  86208. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  86209. if (!lodNode) {
  86210. throw new Error(context + ": Failed to find node " + index);
  86211. }
  86212. nodes.push(lodNode);
  86213. }
  86214. loader._addLoaderPendingData(node);
  86215. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  86216. loader._removeLoaderPendingData(node);
  86217. onComplete();
  86218. });
  86219. });
  86220. };
  86221. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  86222. var _this = this;
  86223. loader._whenAction(function () {
  86224. loader._loadNode(context, nodes[index]);
  86225. }, function () {
  86226. if (index !== nodes.length - 1) {
  86227. var previousNode = nodes[index + 1];
  86228. previousNode.babylonMesh.setEnabled(false);
  86229. }
  86230. if (index === 0) {
  86231. onComplete();
  86232. return;
  86233. }
  86234. setTimeout(function () {
  86235. loader._tryCatchOnError(function () {
  86236. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  86237. });
  86238. }, _this.Delay);
  86239. });
  86240. };
  86241. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  86242. var _this = this;
  86243. return this._loadExtension(context, material, function (context, extension, onComplete) {
  86244. var materials = [material];
  86245. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  86246. var index = _a[_i];
  86247. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  86248. if (!lodMaterial) {
  86249. throw new Error(context + ": Failed to find material " + index);
  86250. }
  86251. materials.push(lodMaterial);
  86252. }
  86253. loader._addLoaderPendingData(material);
  86254. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  86255. loader._removeLoaderPendingData(material);
  86256. onComplete();
  86257. });
  86258. });
  86259. };
  86260. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  86261. var _this = this;
  86262. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  86263. if (index === materials.length - 1) {
  86264. assign(babylonMaterial, isNew);
  86265. // Load the next LOD when the loader is ready to render.
  86266. loader._executeWhenRenderReady(function () {
  86267. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  86268. });
  86269. }
  86270. else {
  86271. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  86272. assign(babylonMaterial, isNew);
  86273. if (index === 0) {
  86274. onComplete();
  86275. }
  86276. else {
  86277. setTimeout(function () {
  86278. loader._tryCatchOnError(function () {
  86279. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  86280. });
  86281. }, _this.Delay);
  86282. }
  86283. });
  86284. }
  86285. });
  86286. };
  86287. return MSFTLOD;
  86288. }(GLTF2.GLTFLoaderExtension));
  86289. Extensions.MSFTLOD = MSFTLOD;
  86290. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  86291. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  86292. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86293. })(BABYLON || (BABYLON = {}));
  86294. //# sourceMappingURL=MSFT_lod.js.map
  86295. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  86296. var BABYLON;
  86297. (function (BABYLON) {
  86298. var GLTF2;
  86299. (function (GLTF2) {
  86300. var Extensions;
  86301. (function (Extensions) {
  86302. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  86303. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  86304. function KHRMaterialsPbrSpecularGlossiness() {
  86305. return _super !== null && _super.apply(this, arguments) || this;
  86306. }
  86307. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  86308. get: function () {
  86309. return "KHR_materials_pbrSpecularGlossiness";
  86310. },
  86311. enumerable: true,
  86312. configurable: true
  86313. });
  86314. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  86315. var _this = this;
  86316. return this._loadExtension(context, material, function (context, extension, onComplete) {
  86317. loader._createPbrMaterial(material);
  86318. loader._loadMaterialBaseProperties(context, material);
  86319. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  86320. assign(material.babylonMaterial, true);
  86321. onComplete();
  86322. });
  86323. };
  86324. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  86325. var babylonMaterial = material.babylonMaterial;
  86326. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  86327. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  86328. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  86329. if (properties.diffuseTexture) {
  86330. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  86331. if (!texture) {
  86332. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  86333. }
  86334. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  86335. }
  86336. if (properties.specularGlossinessTexture) {
  86337. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  86338. if (!texture) {
  86339. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  86340. }
  86341. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  86342. babylonMaterial.reflectivityTexture.hasAlpha = true;
  86343. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  86344. }
  86345. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  86346. };
  86347. return KHRMaterialsPbrSpecularGlossiness;
  86348. }(GLTF2.GLTFLoaderExtension));
  86349. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  86350. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  86351. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  86352. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86353. })(BABYLON || (BABYLON = {}));
  86354. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  86355. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  86356. globalObject["BABYLON"] = BABYLON;
  86357. 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;
  86358. 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 };